Explain the UnboundLocalError exception and how to avoid it?

Technology CommunityCategory: PythonExplain the UnboundLocalError exception and how to avoid it?
VietMX Staff asked 3 years ago
Problem

Consider:

>>> x = 10
>>> def foo():
...     print(x)
...     x += 1

And the output:

>>> foo()
Traceback (most recent call last):
  ...
UnboundLocalError: local variable 'x' referenced before assignment

Why am I getting an UnboundLocalError when the variable has a value?

When you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope. Since the last statement in foo assigns a new value to x, the compiler recognizes it as a local variable. Consequently when the earlier print(x) attempts to print the uninitialized local variable and an error results.

In the example above you can access the outer scope variable by declaring it global:

>>> x = 10
>>> def foobar():
...     global x
...     print(x)
...     x += 1
>>> foobar()
10