Reputation: 809
I believe I have some fundamental misunderstanding of Python global variables and their scope, and I was hoping someone can educate me. Say I have two Python files.
#"GlobalSet.py"
global myVar
myVar = True
print "myVar" in globals()
import GlobalCheck
and
#"GlobalCheck.py"
print "myVar" in globals()
Running "GlobalSet.py" surprisingly results in
True
False
Why isn't "myVar" in the global scope within "GlobalCheck"?
Upvotes: 0
Views: 398
Reputation: 599630
Global in Python means global to the current module. To share variables between modules you need to import them.
Note that the global keyword in your code is doing nothing at all, since myVar is already defined at module level. You would only need to use that keyword if you were modifying the value of myVar inside a function in that module.
Upvotes: 2
Reputation: 1806
The global is within the context of the module. In GlobalCheck.py, if you put
import GlobalSet
print GlobalSet.myVar
that will work. (globals() doesn't appear to work across modules.)
Upvotes: 2