circular imports (don't yell!)
jimh
jim at jim.jim
Fri Mar 22 20:34:42 EST 2002
We have a scenario where we have (and need) circular imports, that is, A
imports B imports C imports A. Now I know there are ways around this, but
we have external dependencies that make it very difficult to use an
alternative, so don't be yelling at me about the design ;)
I have whittled the problem down to 3 files:
a.py
------
from b import *
from c import *
consta = 3
if __name__ == "__main__":
print consta
print constb
print constc
b.py
------
print "in b"
from c import *
constb = 4
constb2 = constc + 10
c.py
------
print "in c"
from a import *
constc = 5
As these are given here, it works. But if I switch the order of the two
imports in a.py, it doesn't work:
Traceback (most recent call last):
File "a.py", line 2, in ?
from c import *
File "c.py", line 2, in ?
from a import *
File "a.py", line 3, in ?
from b import *
File "b.py", line 5, in ?
constb2 = constc + 10
NameError: name 'constc' is not defined
I think this is what is happening:
- a imports c so c is marked as "loaded"
- c imports a
- a imports b
- b imports c, but c is already marked as "loaded", however, it hasn't
REALLY been loaded, thus constc is not yet defined.
Any ideas?
Jim
Thanks.
More information about the Python-list
mailing list