How to Resolve UnboundLocalError in Nested Function Scopes in Python?

Susan Sarandon
Release: 2024-10-21 18:45:02
Original
999 people have browsed it

How to Resolve UnboundLocalError in Nested Function Scopes in Python?

UnboundLocalError in Nested Function Scopes

In Python, accessing a variable defined in an outer function from a nested function can sometimes result in an UnboundLocalError. Consider the following example:

<code class="python">def outer():
    ctr = 0

    def inner():
        ctr += 1

    inner()</code>
Copy after login

Running this code will raise an UnboundLocalError for the variable ctr in the inner function. This error occurs because Python treats ctr as a local variable within the inner function, even though it's defined in the outer function. To resolve this issue, we need to use a mechanism that allows the inner function to access the outer function's scope.

Solution:

Python 3 introduced the nonlocal statement, which permits nonlocal variable modification. By adding nonlocal to the inner function, we explicitly declare ctr as a nonlocal variable, allowing its rebinding within the inner function.

<code class="python">def outer():
    ctr = 0

    def inner():
        nonlocal ctr
        ctr += 1

    inner()</code>
Copy after login

Alternatively, in Python 2, which lacks the nonlocal statement, we can work around this issue by enclosing the counter variable within a list or other data structure to avoid barename rebinding:

<code class="python">ctr = [0]

def inner():
    ctr[0] += 1</code>
Copy after login

This approach maintains the value of ctr within the list ctr, preventing the UnboundLocalError from occurring.

The above is the detailed content of How to Resolve UnboundLocalError in Nested Function Scopes in Python?. 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
Latest Articles by Author
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!