Home  >  Article  >  Backend Development  >  How to Handle UnboundLocalError in Python\'s Nested Function Scopes?

How to Handle UnboundLocalError in Python\'s Nested Function Scopes?

Barbara Streisand
Barbara StreisandOriginal
2024-10-21 18:42:03158browse

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!

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