Assigning to a Variable Anywhere in a Function Makes It Local in Python
A variable that a function only reads is looked up in the enclosing scopes. But if the function assigns to it anywhere in its body, Python treats it as local for the whole function, so reading it before the assignment raises UnboundLocalError.
>>> a = 3
>>> def foo():
... print(a)
...
>>> foo()
3
>>> def coo():
... print(a)
... a += 1
...
>>> coo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in coo
UnboundLocalError: cannot access local variable 'a' where it is not associated with a value
-
The decision is made when the function is compiled, not line by line:
a += 1makesalocal everywhere incoo, including theprintabove it. -
global a(ornonlocal a, for an enclosing function) tells Python to use the outer variable instead:>>> def coo(): ... global a ... print(a) ... a += 1 ... print(a) ... >>> coo() 3 4 -
Usually better still: pass the value in and return the result, rather than changing a global.