Frage

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?

War es hilfreich?

Lösung

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
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top