Possible Duplicate:
Cyclic module dependencies and relative imports in Python
I am trying to understand how sub-packages and relative imports work in Python. I am using Python 3.2.
The following example consists of a package (package
) and a module (package/module.py
) within that package, where that module and the package's init module (package/__init__.py
) use members from each other (only the import
statements are shown). test.py
is launched with the directory containing package
in its sys.path
.
package/__init__.py:
from . import module
package/module.py:
import package
test.py:
import package
This works fine. But when I move package
into another package (lib
), it breaks:
lib/__init__.py:
# empty
lib/package/__init__.py:
from . import module
package/module.py:
from .. import package
test.py:
from lib import package
Running test.py
will fail with the following stack trace:
Traceback (most recent call last):
File "test.py", line 1, in <module>
from lib import package
File "/Users/ims/test/lib/package/__init__.py", line 1, in <module>
from . import module
File "/Users/ims/test/lib/package/module.py", line 1, in <module>
from .. import package
ImportError: cannot import name package
My questions are:
- What is the reason for the cyclic import to work inside a top-level package but not inside a sub-package?
- Is there a work-around for this problem?