I have two python modules:
//// funcs.py
from classes import *
def func():
d = D()
print "func"
if __name__ == "__main__":
c = C()
//// classes.py
from funcs import *
class C:
def __init__(self):
print "C class"
func()
class D:
def __init__(self):
print "D class"
Running funcs.py yields a NameError saying that "global name 'D' is not defined". However if I comment out the creation of the D() instance, everything works fine.
Why does this happen?
Thanks
2 Answers 2
This one works fine without complicating your code:
///funcs.py
import classes
def func():
d = classes.D()
print "func"
if __name__ == "__main__":
c = classes.C()
///classes.py
import funcs
class C:
def __init__(self):
print "C class"
funcs.func()
class D:
def __init__(self):
print "D class"
Sometimes it's much better to use simple import, than from ... import ....
There is quite good article on that:
http://effbot.org/zone/import-confusion.htm
Comments
The problem occurs due to the attempt to use a cyclically imported module during module initialization. To clarify, using the "from module use *" requires that a module be compiled. Instead if you switch to using "import module" in both cases, it should work fine.
1 Comment
from m import * copies everything that's in the module at that point in time while import m gives a reference to the module object - and hence makes later modifications visible.