Suppose I have a file:
# main.py
import foo
my_global = "global variable"
foo.print_global()
and another:
# foo.py
def print_global():
global my_global
print(my_global)
Why do I get NameError: name 'my_global' is not defined
when I run main.py
please? How can I make my_global
available to foo.py
? Is it a bad idea to try - maybe I should always pass values as function arguments in this kind of situation?
Python doesn't have process-wide globals, only module-level globals. foo.print_global
looks at foo.my_global
, not main.my_global
, which is what you set. That is, the scope that print_global
uses for global variables is determined when print_global
is defined , not when it is called .
This would do what you expect.
import foo
foo.my_global = "global variable"
foo.print_global()
Note that foo.py
should not rely on someone else creating its global variable(s) before calling print_global
; at the very least, foo.py
should initialize my_global
to None
, if not some other default value.
Also note that the solution above is not the same as
from foo import my_global
my_global = "..."
This creates a new global name in the current module, which is initialized using the current value of foo.my_global
. The subsequent assignment changes the name of the "local" global variable, not foo.my_global
.
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.