How can I fix UnboundLocalError local variable referenced before assignment?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
UnboundLocalError in Python means code tries to read a local variable before it gets assigned in that function scope. It often appears when a variable name is reused unintentionally or assignment happens only in one branch. The fix is to make scope and initialization explicit.
Why This Error Happens
Python decides variable scope at function compile time. If a variable is assigned anywhere in a function, Python treats it as local in that function.
Example that fails:
Because x is local inside f, print(x) reads it before assignment.
Fix with Explicit Initialization
Initialize local variable before use.
This avoids branch-dependent uninitialized state.
Fix Branch-Dependent Assignment
A common bug is assigning only inside one condition.
Always assign in all branches before returning or reading.
Use global Only When Intentional
If you truly need to write global variable from function, declare global explicitly.
Use this sparingly. Global mutation often makes code harder to reason about.
Use nonlocal in Nested Functions
Nested closures can trigger similar errors when inner function writes outer variable.
Without nonlocal, assignment creates new local variable and read-before-assign errors can appear.
Refactor to Reduce Scope Confusion
Large functions with reused names are more error-prone. Refactor into smaller functions and pass values explicitly.
A practical pattern:
- Compute value in one function.
- Return it explicitly.
- Avoid reading mutable outer state unless necessary.
This reduces accidental variable shadowing.
Watch Out for try and except Paths
Assignments inside try block can be skipped if exception occurs.
Pre-initializing value avoids unbound local errors after exceptions.
Debugging Checklist
When this error appears:
- Find variable named in exception.
- Search all assignments to that name in function.
- Confirm assignment happens before first read on every path.
- Check nested scope and
globalornonlocalusage. - Rename variables to avoid shadowing outer names.
This sequence usually identifies root cause quickly.
Preventive Practices
Use linters and type checkers. Tools like ruff or pylint often flag potential unbound local usage before runtime.
Also keep function scope narrow and naming explicit. Style discipline prevents many scope bugs.
Comprehension and Closure Edge Cases
Scope confusion can also happen in closures and loops that capture variables. If closure behavior seems inconsistent, inspect captured names and initialization order carefully.
Binding loop variable explicitly in lambda defaults avoids unexpected late-binding behavior that is often mistaken for scope bugs.
Common Pitfalls
- Reading variable before assignment in same function scope.
- Assigning variable in only one conditional branch.
- Forgetting
nonlocalin nested function updates. - Mutating global state unintentionally.
- Reusing outer variable names and causing shadowing confusion.
Summary
- '
UnboundLocalErroris a scope and initialization issue.' - Assign local variables before any read on all code paths.
- Use
globalandnonlocalonly when intentional. - Refactor large functions to reduce shadowing and scope complexity.
- Use linters to catch scope bugs early.

