Home > Backend Development > Python Tutorial > How Can I Modify Variables in Enclosing Scopes in Python?

How Can I Modify Variables in Enclosing Scopes in Python?

Linda Hamilton
Release: 2024-12-11 16:20:14
Original
590 people have browsed it

How Can I Modify Variables in Enclosing Scopes in Python?

Modifying Variables in Enclosing Scope: A Pythonesque Conundrum

In Python, the concept of scope governs the visibility and accessibility of variables. When dealing with nested and enclosing scopes, it's not always straightforward to modify variables in an outer scope.

The Problem: UnboundLocalError

Consider the following code snippet:

def A():
    b = 1
    def B():
        # Access 'b', no problem
        print(b)
        # Attempt to modify 'b'
        b = 2  # UnboundLocalError
    B()
A()
Copy after login

Here, the variable b is defined in the enclosing scope of B, but it's not global. Trying to modify b directly within B results in an UnboundLocalError because b is not declared as a local variable in B.

The Solution: Embrace the Non-Global Scope

In Python 3, the nonlocal keyword comes to the rescue. It allows you to modify variables in an enclosing, non-global scope.

def A():
    b = 1
    def B():
        nonlocal b
        b = 2
    B()
    print(b)  # Output: 2
Copy after login

Python 2's Alternative: Mutability to the Rescue

While Python 3 has the convenient nonlocal keyword, Python 2 doesn't provide a direct solution. A workaround is to use mutable objects (e.g., lists or dictionaries) and mutate their values instead of reassigning variables.

def foo():
    a = []
    def bar():
        a.append(1)
    bar()
    bar()
    print(a)  # Output: [1, 1]
Copy after login

By manipulating the list a, which is an object, you can essentially modify its content while adhering to Python 2's scope rules.

The above is the detailed content of How Can I Modify Variables in Enclosing Scopes in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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