Helpful Information
 
 
Category: Python
Can you preventing import dependency loops?

I'm having a problem where two modules depend on each other. I am using simple import statements, but it would create an endless loop as the two files try to import each other. Obviously python prevents this, but it only gets to a certain point in each file. This is rather hard to explain by text, so I'll try an explain by example.

You start off by parsing a.py

a.py


print "a"

import b

def d():
print "d"


b.py


print "b"

import a

def c():
print "c"
d();

c()


This will fail, because d has not yet been defined. The problem is, that code in b.py depends on code in a.py, and vice versa. Here is the output and eventual stacktrace.



a
b
a
c
Traceback (most recent call last):
File "C:\Documents and Settings\xconspirisist\Desktop\a.py", line 3, in <module>
import b
File "C:\Documents and Settings\xconspirisist\Desktop\b.py", line 9, in <module>
c()
File "C:\Documents and Settings\xconspirisist\Desktop\b.py", line 7, in c
d();
NameError: global name 'd' is not defined


Any help would be greatly appreciated

Try the from statment










privacy (GDPR)