By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,345 Members | 1,783 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,345 IT Pros & Developers. It's quick & easy.

Circular imports

P: n/a
Although it may not be good design, I have a situation such that module A
imports module B and module B imports module A. This appears to be causing
problems when I use Python with mod_python/Apache and PSP programming. 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 ?
Jul 18 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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

Jul 18 '05 #2

P: n/a
Greg Ewing wrote:
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.


Thanks for the info. I was definitely doing some of this and causing myself
problems. Now I understand why.
Jul 18 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.