0

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"?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.)

2 Comments

You can also do from GlobalSet import myVar
re: globals() across modules: Python doesn't have one single global scope. Rather, each module (including __main__) has a single module-level scope, which is what the global keyword in a function refers to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.