Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the logic behind this python global scoping magic?

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?

like image 455
monoceres Avatar asked Mar 25 '23 00:03

monoceres


1 Answers

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
like image 175
Martijn Pieters Avatar answered Apr 02 '23 10:04

Martijn Pieters