UnboundLocalError
UnboundLocalError: local variable 'x' referenced before assignment
Traceback
Traceback (most recent call last):
File "main.py", line 5, in <module>
foo()
UnboundLocalError: local variable 'x' referenced before assignmentWhat causes this error
A variable was used before being assigned in the local scope. Python determines at compile time that the name is local (because it is assigned somewhere in the function), so reading it before the assignment line raises this error.
How to fix it
Ensure variables are assigned before use. Use `global` to reference global variables you want to modify. Use `nonlocal` for enclosing scope variables. Restructure code so assignments come before reads.
Code that causes this error
x = 10
def foo():
print(x)
x = 20 # makes x local for entire function
foo()Fixed code
x = 10
def foo():
global x
print(x)
x = 20
foo()About UnboundLocalError
An UnboundLocalError is raised when a local variable is referenced before it has been assigned a value. This is a subclass of NameError. The error often confuses developers because the variable may appear to be defined — but Python's scoping rules are the culprit.
When Python compiles a function, it scans for all assignments and marks those names as local variables for the entire function body. If you reference such a name before the assignment statement executes, UnboundLocalError is raised, even if a global or enclosing variable with the same name exists. The most common trigger is reading a variable, then assigning to it later in the function, which makes Python treat it as local from the start.
The `global` keyword declares that a name refers to the global scope, and `nonlocal` (Python 3) declares it refers to the nearest enclosing scope — both prevent UnboundLocalError when you need to assign to outer variables.
Common scenarios
Typos in variable or function names that are hard to spot
Using a variable before it has been assigned a value
Forgetting to import a module or function before using it
Variable shadowing issues between local and global scope