Home >Backend Development >Python Tutorial >How to Handle UnboundLocalError in Python\'s Nested Function Scopes?
Nested Function Scope and UnboundLocalError
In Python, nested function scopes can lead to issues with local variables. Consider the following code:
def outer(): ctr = 0 def inner(): ctr += 1 inner()
When executing this code, you may encounter an UnboundLocalError for the variable 'ctr' within the inner function. This error occurs because the inner function attempts to modify the 'ctr' variable defined in the outer function, but it's not recognized as a local variable within the inner scope.
To resolve this issue, there are two approaches:
Python 3:
In Python 3, the nonlocal statement allows you to modify non-local variables within a nested function:
def outer(): ctr = 0 def inner(): nonlocal ctr ctr += 1 inner()
Python 2:
Python 2 lacks the nonlocal statement, but a workaround is to use a data structure to hold the variable instead of directly using a variable name:
def outer(): ctr = [0] # Store the counter in a list def inner(): ctr[0] += 1 inner()
By using this approach, you avoid barename rebinding and ensure that the inner function can modify the intended variable.
The above is the detailed content of How to Handle UnboundLocalError in Python\'s Nested Function Scopes?. For more information, please follow other related articles on the PHP Chinese website!