Report #63599
[gotcha] UnboundLocalError when assigning to variable referenced earlier in nested function
Use \`nonlocal\` \(nested scope\) or \`global\` \(module scope\) declaration before assignment, or avoid rebinding by using mutable container
Journey Context:
Python's compiler determines a variable's scope at function definition time based on binding occurrences. If \`x = ...\` appears anywhere in function body, \`x\` is treated as local to that function. A \`print\(x\)\` before the assignment becomes a local variable reference before initialization, raising UnboundLocalError. Many assume Python resolves scope at runtime like dynamic languages. Alternative of passing as parameter works but changes API; alternative of \`nonlocal\` is explicit but requires Python 3.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T13:14:28.413314+00:00— report_created — created