Cyclic imports

James rent.lupin.road at gmail.com
Fri Jun 27 05:40:42 CEST 2008


Hi all,
I'm looking for some advice dealing with cyclic, cross-package
imports.

I've created the following demo file structure:
./a/__init__.py
./a/a.py
./b/__init__.py
./b/b.py
./main.py

a.py imports a class from b.py and vice versa, and main.py imports
them both.

However, because a.py has not been completely read by the time it gets
to the:
from b import b
line, the
from a import a
line in b.py fails with an import error (stack trace at the end).

I hope that's clear: basically, because of the cyclic import, I see
incomplete modules which can't be imported.

Can I have this module hierarchy in some other way?

Thanks,
James

Stack trace from example:
  File "main.py", line 1, in <module>
    from a import a
  File "/Users/james/tmp/python/a/a.py", line 1, in <module>
    from b import b
  File "/Users/james/tmp/python/b/b.py", line 1, in <module>
    from a import a
ImportError: cannot import name a



More information about the Python-list mailing list