Consider this code:
Var='global'
def func():
Var='local'
#global Var
print Var
I'm trying to print the global variable even though I have a local variable with the same name. However, when I use the keyword global, it gives me an error.
Is there a way to do this?
I would also appreciate an explanation of why global gives an error.
Use globals()
which is a built-in function. From documentation for globals()
:
Return a dictionary representing the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called).
Var='global'
def func():
Var='local'
print(globals()['Var'])
Reply to your comment:
First try this:
Var='global'
def func():
Var='local'
global Var
Var = 'Global'
print(Var)
func()
print(Var)
Amazed? What's going on here is that Python assumes that any variable name that is assigned to, within a function, is local to that function unless explicitly told otherwise. If it is only reading from a name, and the name doesn't exist locally, it will try to look up the name in any containing scopes (e.g. the module's global scope). In your case there is a local variable Var
with the same name as the global Var
, so the global variable is shadowed. Since Var
exists locally, it does not need to be looked up in any containing scopes, and thus the local variable is used. However, when you change the value of Var
(using global Var
statement) Python uses the global variable, which can be seen by printing global Var
in the global scope. As a matter of fact, the global
keyword is actually used to modify a global variable from any local sub-scope. See here. Hope it is clear!
P.S.: I gathered the knowledge from Jeff Shannon's answer.