Circular imports (again)

Ethan Furman ethan at
Mon Aug 9 19:33:15 CEST 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.
import b
def spam():
def foo():
     print "my circular-import-fu is strong!" # to amuse myself only!)
import a
def eggs():
     print 'sunnyside?'
def ham():

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

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

Hope this helps.


More information about the Python-list mailing list