I know that a global variable is created in the main scope, and to assign a value to it inside of a function, we need to use the keyword global
. However, to use it (for example, to print it) inside a function, we don't need to use the keyword global
. For example:
s = 5
def foo1():
print(s)
s = 5
def foo2():
global s
s = 6
print(s)
Now I try to do this:
s = 5
def foo3():
print(s)
s = 'bbb'
print(s)
and I call foo3()
. I know this is a mistake since I am trying to assign a global variable inside a function without the use of the keyword global
:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in foo3
UnboundLocalError: local variable 's' referenced before assignment
However, I'm interested in why the first print(s)
in foo3()
is not executed, and I get the error when it tries to run it. How can Python recognize that s
is a local variable before I even try to apply an assignment (without the keyword global
)?
I hypothesise that when the function is defined, Python declares all its local variables according to the function code, and therefore it knows before the assignment that s
is a local variable, and not the global. I tried to find information about this but couldn't (I'm sure there is information that I didn't see).