I was checking how does global keyword work for a project when I run by mistake the CODE1, which worked in a way that I did not expect. The global keyword takes effect in the function even if it is not in an executed part (i.e. in a if which condition is not true).
I have been looking around for questions about the global keyword in python but I could not find a response to this. I saw: Python global keyword behavior, global keyword in python, Using global variables in a function
The most interesting, and I think it may have to do something with it is this one (but I am not sure): Python global keyword
Below, the three Minimal Reproducible Examples of the code I used are shown:
CODE1 (with global keyword):
a = 0
def my_function():
b=2
if b==0:
print("first if")
global a
if b==2:
print("second if")
a = 2
print("func -> a", a)
print("func -> b", b)
if __name__ == '__main__':
my_function()
print("main -> a", a)
Result:
second if
func -> a 2
func -> b 2
main -> a 2
CODE2 (without global keyword):
a = 0
def my_function():
b=2
if b==0:
print("first if")
if b==2:
print("second if")
a = 2
print("func -> a", a)
print("func -> b", b)
if __name__ == '__main__':
my_function()
print("main -> a", a)
Result:
second if
func -> a 2
func -> b 2
main -> a 0
CODE3 (with global keyword, but inverted if statements):
a = 0
def my_function():
b=2
if b==2:
print("second if")
a = 2
print("func -> a", a)
print("func -> b", b)
if b==0:
print("first if")
global a
if __name__ == '__main__':
my_function()
print("main -> a", a)
Result:
File "global_var_test.py", line 18
global a
^
SyntaxError: name 'a' is used prior to global declaration
As it can be seen, if b==0:
is always False and if b==2:
is always True (print confirms it). I would expect that CODE1 gives the same result as CODE2 as global a
would not be executed in the first example, so it would be the same than ommiting it. But it gives an innesperate result, in which the global keyword takes effect anyway and the global variable a is changed to value 2. After this, I tested with CODE3 thinking the global keyword would be visible in all the function regardless of its position, and then CODE3 should give the same result as CODE1. Again I was wrong, it worked like if global a
was going to be executed (and then it was after the asignation and an exception is raised).
Then, my final question is: ¿does the global keyword (and maybe others like nonlocal, etc.) have visibility in the code in the order that is written but independently of what is being executed?
Please help me in clarifying this.