Why Python Raises UnboundLocalError and How to Fix It Correctly
Python's UnboundLocalError confuses developers because the variable in question visibly exists elsewhere in the code, yet the error still occurs. The root cause is that Python scans an entire function body before executing it, and any variable assigned anywhere inside the function is pre-marked as local throughout that function. This means a line like 'count += 1' causes Python to treat 'count' as a local variable, making the outer module-level 'count' inaccessible within that function. The cleanest fix is usually to pass the value as a parameter and return the updated result, avoiding shared mutable state altogether. When a function must modify a module-level variable, the 'global' keyword explicitly instructs Python to reference the outer scope instead of creating a local shadow.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.

Discussion (0)
Log in to join the discussion and vote.
Log in