21.6 Scope Pitfalls: UnboundLocalError and Late-Binding Closures
One of the most common and initially confusing issues encountered by Python programmers is the UnboundLocalError. This error arises from a misunderstanding of how Python’s scoping rules interact with variable assignment. The core principle is that any variable to which a value is assigned anywhere within a function body is treated as a local variable for the entire scope of that function, unless explicitly declared otherwise. The UnboundLocalError Explained This error occurs when a local variable is referenced before it has been assigned a value. The confusion often stems from the fact that a variable of the same name exists in an enclosing scope, leading the programmer to believe the inner function will use that value. However, because an assignment exists later in the function, Python binds the variable name to the local scope from the outset. When the code tries to read from this local variable before it has been assigned, the UnboundLocalError is raised.