python scoping ai_generated true

UnboundLocalError: cannot access local variable 'x' referred to before assignment

ID: python/unboundlocalerror

Also available as: JSON · Markdown
98%Fix Rate
97%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
311 active

Root Cause

Variable referenced before assignment in local scope, often caused by reassigning a global/outer variable without nonlocal/global declaration.

generic

Workarounds

  1. 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

  2. 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:

  1. Adding a try/except around the assignment 85% fail

    Masks the scoping issue; variable is still unbound on the failing path

  2. 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: