Home >Backend Development >Python Tutorial >How to Resolve UnboundLocalError in Nested Function Scopes in Python?

How to Resolve UnboundLocalError in Nested Function Scopes in Python?

Susan Sarandon
Susan SarandonOriginal
2024-10-21 18:45:021083browse

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>

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>

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>

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!

Statement:
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