Description
I have a package structure where various modules need to obtain information from different ones and therefore I use relative imports. It happens that those relative imports are nested in some way.
I'll just present you the package structure I have:
.
├── core
│ ├── __init__.py
│ ├── sub1
│ │ ├── __init__.py
│ │ └── mod1.py
│ └── sub2
│ ├── __init__.py
│ ├── mod1.py
│ └── sub1
│ ├── __init__.py
│ └── mod1.py
└── main.py
The files contain the following statements:
main.py:
print __name__
import core.sub2.mod1
core/sub2/mod1.py
print __name__
import sub1.mod1
core/sub2/sub1/mod1.py
print __name__
from ...sub1 import mod1
core/sub1/mod1.py
print __name__
from ..sub2 import mod1
Visualization
A visualization of the imports:
Problem
When I run python main.py
I get the following error (I substituted the absolute file paths with ./<path-to-file>
):
__main__
core.sub2.mod1
core.sub2.sub1.mod1
core.sub1.mod1
Traceback (most recent call last):
File "main.py", line 2, in <module>
import core.sub2.mod1
File "./core/sub2/mod1.py", line 2, in <module>
import sub1.mod1
File "./core/sub2/sub1/mod1.py", line 2, in <module>
from ...sub1 import mod1
File "./core/sub1/mod1.py", line 2, in <module>
from ..sub2 import mod1
ImportError: cannot import name mod1
From this question I learned that python uses the __name__
attribute of a module to resolve its location within the package. So I printed all the names of the modules and they seem to be alright! Why do I get this ImportError
then? And how can I make all the imports work?