Reputation: 81
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
Upvotes: 0
Views: 38
Reputation: 828
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
Upvotes: 1