python
scoping
ai_generated
true
UnboundLocalError: cannot access local variable 'x' referred to before assignment
ID: python/unboundlocalerror
98%Fix Rate
97%Confidence
50Evidence
2023-01-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 311 | active | — | — | — |
Root Cause
Variable referenced before assignment in local scope, often caused by reassigning a global/outer variable without nonlocal/global declaration.
genericWorkarounds
-
95% success Add 'nonlocal' or 'global' declaration if intending to modify outer scope variable
Use nonlocal x or global x at the top of the inner function
Sources: https://docs.python.org/3/reference/simple_stmts.html#the-nonlocal-statement
-
92% success Restructure to avoid shadowing — rename the local variable
Use a different name for the local variable so it doesn't shadow the outer one
Dead Ends
Common approaches that don't work:
-
Adding a try/except around the assignment
85% fail
Masks the scoping issue; variable is still unbound on the failing path
-
Initializing the variable to None at function top
55% fail
Hides the real bug if the None path is never intended
Error Chain
Frequently confused with: