How to Handle Unbound Local Variable Errors in Nested Function Scopes?

DDD
Release: 2024-10-21 18:42:29
Original
621 people have browsed it

How to Handle Unbound Local Variable Errors in Nested Function Scopes?

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>
Copy after login

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
Copy after login

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>
Copy after login

For Python 2 users, alternative approaches are necessary:

  • Barename Removal:
    Remove the bare ctr variable and place it within a data structure or as an attribute. For instance, ctr = [0].
  • Variable Reassignment:
    Reassign the ctr variable within the inner function instead of using barename rebinding: ctr = ctr 1.

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!