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

Barbara Streisand
Release: 2024-10-21 18:42:03
Original
173 people have browsed it

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

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

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

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!

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!