Report #104718
[gotcha] UnboundLocalError when assigning to a variable that is also read before assignment inside a function, even when a global variable of the same name exists
Declare the variable as \`global\` \(or \`nonlocal\`\) if you intend to modify it. If you only need to read a global, do not assign to the same name anywhere in the function. Use a different local name to avoid shadowing.
Journey Context:
Python determines at compile time whether a name is local or global based on the presence of any assignment to that name in the function body. If you assign to \`x\` anywhere, Python treats \`x\` as local throughout the entire function. When you then try to read \`x\` before the assignment, no local binding exists yet, so it raises \`UnboundLocalError\` – even though a global \`x\` exists. Common workarounds: use \`global x\` at the top, or avoid the assignment entirely by using a different variable name. The alternative of defaulting to global when no local assignment exists would break the ability to have truly local variables and would make closures harder. The current design is intentional and well-documented, but it catches many newcomers off guard.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-10-04T20:03:53.060523+00:00— report_created — created