0

in my case I have folder structure as :

|- category 
|  |- sub-category
|    |- do_something.py
|
|- package
|  | -module.py

I want to import function present in module.py inside do_something.py, something like :

from ..package.module import func_1

How should I do this , I have tried relative path but keep getting error like :

ImportError: attempted relative import with no known parent package

1

2 Answers 2

1

The error is because python is viewing the category and package folders as different packages.

In order for python to view them both as a sub-package of your program, you need to run your program from a parent directory of both folders. if you run do_something.py directly, then you'd get an error because python is unsure if the current package (category) has access to the package folder. Also, remember your init.py files, and don't use hyphens in the folders/files names

|- category 
   | __init__.py
|  |- sub_category
     | __init__.py
|    |- do_something.py
|
|- package
   | __init__.py
|  | -module.py
|- FILE_TO_EXECUTE.py

#do_something.py

from ...package.module import func_1

#FILE_TO_EXECUTE.py

from category.sub_category.do_something import *

#SHELL

python FILE_TO_EXECUTE.py

Since both the package and category folders are children of the current directory, python knows they are sub-packages and can do relative imports between them

Sign up to request clarification or add additional context in comments.

Comments

0

Try to use Absolute path:

from package.module import func_1

2 Comments

I am getting error like this when i tried your suggetion : No module named 'package_name'
@SomitraGupta hm, did you have in your code?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.