Reputation: 1899
Why does the below work in Python, without declaring a in the global scope first?
def setA():
global a
a = 5
def printA():
print a
setA()
printA()
It seems to me that this is the correct way to do it:
a = None
def setA():
global a
a = 5
def printA():
print a
setA()
printA()
Upvotes: 2
Views: 339
Reputation: 251383
Basically for the same reason that a = 5
works to create a new local variable: when you assign to a variable, Python doesn't care whether it exists already or not. The global
statement simply means "any uses of the following name in this scope are now considered to be operating in global scope".
You can do a = 5
at the module top level whether a
exists already or not. So you can do global a; a = 5
inside a function. global
makes the assignment inside the function work just like the one at the global level, including the fact that it doesn't matter whether the name already exists or not.
Upvotes: 8