Resolving UnboundLocalError in Nested Function Scopes
The Python interpreter encounters an UnboundLocalError when accessing an unbound local variable within a nested function. This issue arises when a nested function attempts to modify a variable declared within the outer function.
Example:
Consider the following code:
<code class="python">def outer(): ctr = 0 def inner(): ctr += 1 inner()</code>
Upon executing this code, the interpreter generates the following error:
Traceback (most recent call last): File "foo.py", line 9, in <module> outer() File "foo.py", line 7, in outer inner() File "foo.py", line 5, in inner ctr += 1 UnboundLocalError: local variable 'ctr' referenced before assignment
Cause:
Despite having nested scopes, the inner function cannot access the 'ctr' variable directly because it is defined in the outer function. This results in an unbound variable, triggering the UnboundLocalError.
Solution:
Python 3 offers the 'nonlocal' statement to enable variable rebinding in nested scopes. Modifying the code to include 'nonlocal' resolves the issue:
<code class="python">def outer(): ctr = 0 def inner(): nonlocal ctr ctr += 1 inner()</code>
For Python 2 users, alternative approaches are necessary:
The above is the detailed content of How to Handle Unbound Local Variable Errors in Nested Function Scopes?. For more information, please follow other related articles on the PHP Chinese website!