I was messing around with the scoping in python and found something that I think is rather strange:
g = 5
def foo(a):
if a:
global g
g = 10
else:
g = 20
print("global g: ",g)
foo(False)
print("global g: ",g) # 20?! What?
foo(True)
print("global g: ",g)
My believe was that the second print should have been "5" since the global statement was never executed, but clearly, the output is 20(!).
What's the logic behind this?
The global
keyword is used by the python compiler to mark a name in the function scope as global.
As soon as you use it anywhere in the function, that name is no longer a local name.
Note that if
does not introduce a new scope, only functions and modules do (with classes, list, dict and set comprehensions being a special cases of function scopes).
A (hard to read and non-pythonic) work-around would be to use the globals()
function:
def foo(a):
if a:
globals()['g'] = 10
else:
g = 20
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With