I have two Python files:
b.py
:
def buzz():
foobar = Foobar()
c.py
:
from b import buzz
class Foobar:
pass
buzz()
Running python c.py
raises:
NameError: name 'Foobar' is not defined
Looks like there is a basic Python's import mechanism I still don't understand. I would expect that, when buzz()
is called, it has dynamically access to the environment now containing Foobar
.
Of course (?), if I replace the importation of buzz
by its definition, it works:
d.py
:
def buzz():
foobar = Foobar()
class Foobar:
pass
buzz()
Context.
This may be an XY-problem. Ultimately, I want to be able to change the behaviour of buzz
depending on which Foobar
variant has previously been imported. However, I would be interested in understanding why b.py
/ c.py
fails.
buzz
function's definition is in module "b.py". This means when the body of the buzz
is being executed( buzz()
in c.py), interpreter jumps into module b
. Module b
's global namespace is where body of the buzz
function can access global variables not c
's global namespace and of course there is no "Foobar"
in module b
's globals()
.
In LEGB rule, "G" points to the module's global namespace which the interpreter is currently in, not other modules' global namespace.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.