In Python, an UnboundLocalError occurs when a local variable is referenced before it has been assigned a value. Unlike other programming languages, Python doesn't require explicit variable declarations. Instead, variables are bound to values when assigned.
One way to trigger an UnboundLocalError is by accessing an unassigned variable:
>>> foobar Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'foobar' is not defined
Another way is when an assignment operation fails to execute, such as within a conditional block:
def foo(): if False: spam = 'eggs' print(spam) >>> foo() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 4, in foo UnboundLocalError: local variable 'spam' referenced before assignment
In Python, names are bound to values through various operations: assignment, function parameters, import statements, exception handlers, and context managers. When a name is bound in a function scope, it becomes a local variable. To access a global variable within a function, a global or nonlocal statement must be used (in Python 3).
For example, the following function attempts to access a global variable foo but fails because it's bound within the function scope:
foo = None def bar(): if False: foo = 'spam' print(foo) >>> bar() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 4, in bar UnboundLocalError: local variable 'foo' referenced before assignment
However, using global foo fixes the issue:
foo = None def bar(): global foo if False: foo = 'spam' print(foo) >>> bar() None
Understanding the concept of variable binding is crucial to avoid UnboundLocalErrors in Python.
The above is the detailed content of Why Do I Get an UnboundLocalError in Python?. For more information, please follow other related articles on the PHP Chinese website!