Circular imports (again)

Ethan Furman ethan at stoneleaf.us
Mon Aug 9 13:33:15 EDT 2010


Frank Millman wrote:
> Hi all
> 
> I know the problems related to circular imports...
 >
> It has just happened again. I have organised my code into three modules, 
> each representing a fairly cohesive functional area of the overall 
> application. However, there really are times when Module A wants to 
> invoke something from Module B, ditto for B and C, and ditto for C and A.

I believe the issue arises when you have top-level code (module global 
code, or unindented code for the visual) that is calling the other 
module.  If you keep your references to the other module in functions, 
you should be able to have your imports at module level.

The below works fine.

a.py
-----
import b
def spam():
     b.eggs()
def foo():
     print "my circular-import-fu is strong!" # to amuse myself only!)
-----

b.py
-----
import a
def eggs():
     print 'sunnyside?'
def ham():
     a.foo()
-----

If you put an <a.spam()> in b.py, then you get:

Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "a.py", line 1, in <module>
     import b
   File "b.py", line 3, in <module>
     a.spam()
AttributeError: 'module' object has no attribute 'spam'


Hope this helps.

~Ethan~



More information about the Python-list mailing list