What is the logic of this global python chip?

I was messing around with the scope in python and found something that, in my opinion, 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) 

I believe that the second fingerprint should have been "5", since the global operator has never been executed, but, obviously, the result is 20 (!).

What is the logic behind this?

+4
source share
1 answer

global keyword is used by the python compiler to designate a function name as global.

Once you use it anywhere in a function, that name is no longer a local name.

Please note that if does not introduce a new scope, only functions and modules (with classes, lists, dict and established understandings are special cases of function areas).

A (hard to read and non-python) job will be to use the globals() function:

 def foo(a): if a: globals()['g'] = 10 else: g = 20 
+7
source

Source: https://habr.com/ru/post/1480337/


All Articles