Circular imports

Greg Ewing greg at cosc.canterbury.ac.nz
Tue May 18 23:45:47 EDT 2004


Edward Diener wrote:
> Can
> anybody tell me if there are any situations where circular imports cause
> problems and, other than a redesign to eliminate it, if there are any other
> ways around those problems ?

Circular imports can cause problems in this situation:

   # module A
   import B

   def foo():
     print "Fooey"

   # module B
   from A import foo

   def blarg():
     foo()


If module A gets imported first, it immediately
imports B, which tries to import foo from A before
it's been defined.

The problem can be avoided by rewriting B as follows:

   # module B
   import A

   def blarg():
     A.foo()

This defers the lookup of foo in A until B.blarg
is called, by which time A will hopefully have
finished initialising itself.

In general, if circular imports are involved, always
use "import X" and refer to "X.n", rather than using
"from X import n". This will avoid most circular
import problems.

-- 
Greg Ewing, Computer Science Dept,
University of Canterbury,	
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg




More information about the Python-list mailing list