Reputation: 3
I have a structure like this:
project_dir/
a/
b/
to_import.py
__init__.py
__init__.py
c/
main.py
__init__.py
I need to import to_import.py
from main.py
. In main.py
I write
from ..a.b.to_import import something
I have an error ImportError: attempted relative import with no known parent package
I put __init__.py
everywhere because I saw an advice to do it. Also, I do it in PyCharm
Upvotes: 0
Views: 40
Reputation: 13049
I would suggest using an absolute import:
from project_dir.a.b.to_import import something
If the parent directory of project_dir
is not in your sys.path
and it is not convenient to set PYTHONPATH
environment variable to ensure this before calling python, then you could force it by putting the following into your main.py
before the import
statement shown above:
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), "../.."))
Upvotes: 1