Python's documentation explains that an UnboundLocalError occurs when a local variable is accessed before it has been assigned a value. However, it mentions that Python does not enforce declarations. This raises the question: how can a variable be "unbound" if it has not been declared?
In Python, variable binding occurs through assignments, loops, functions, imports, exception handling, and context management. Bindings determine the scope of a variable. A name is considered local if it is bound within a function or method, unless explicitly marked as global or nonlocal using the appropriate statements.
An unbound name refers to a variable that has been referenced before being bound. This differs from an undefined name, which has not yet been created or assigned. When an unbound name is encountered, Python raises an UnboundLocalError.
Consider the following code:
def foo(): if False: spam = 'eggs' print(spam)
Executing foo() will result in an UnboundLocalError. The spam variable is referenced in print(spam) without ever being assigned a value. Even though it is defined within the if statement, the statement is not executed, so spam remains unbound.
To prevent UnboundLocalError, ensure that local variables are assigned a value before referencing them. Alternatively, explicitly declare global variables using the global statement or nonlocal variables using the nonlocal statement.
In summary, a name becomes unbound when it is referenced before being bound within the current scope. This occurs because Python does not require variable declarations, allowing binding operations to occur anywhere within a code block. Using proper assignment and scope management can help avoid UnboundLocalError exceptions.
The above is the detailed content of When and How Does an UnboundLocalError Occur in Python?. For more information, please follow other related articles on the PHP Chinese website!