I use the following code to experiment with nonlocal
def a():
b = 5
print(f"b (1) = {b}")
def c():
#nonlocal b
print(f"b (2) = {b}")
b = 3
c()
a()
When I comment out nonlocal I get the following error:
Traceback (most recent call last):
File "<string>", line 10, in <module>
File "<string>", line 8, in a
File "<string>", line 6, in c
UnboundLocalError: cannot access local variable 'b' where it is not associated with a value
I expected the value of variable b from function a to be printed out on the console and then a locale variable of the same name would be created. But obviously when the function is parsed, it is noted that there is a local variable called b in the function c, but it is not yet assigned a value, as this is done at runtime. Are my thoughts correct and are there sources where I can read more about this?