Circular imports

E

Edward Diener

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 ?
 
G

Greg Ewing

Edward said:
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.
 
E

Edward Diener

Greg said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,679
Members
48,796
Latest member
Greg L.

Latest Threads

Top