Python scope / namespace issue

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 gives a NameError saying that the "global name" D "is not defined." However, if I comment on creating an instance of D (), everything will be fine.

Why is this happening?

thanks

+4
source share
2 answers

This works just 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 is much easier to use simple imports than from ... import ... There is a good article: http://effbot.org/zone/import-confusion.htm

+5
source

The problem arises from trying to use a cyclically imported module during module initialization. To clarify, the use of "out of use of the module" requires that the module be compiled. Instead, if you switch to using the "import module" in both cases, it should work fine.

+2
source

Source: https://habr.com/ru/post/1369464/


All Articles