Home >Backend Development >Python Tutorial >How Can I Modify Non-Global Variables in Outer Scopes in Python?

How Can I Modify Non-Global Variables in Outer Scopes in Python?

Barbara Streisand
Barbara StreisandOriginal
2024-12-16 12:06:15315browse

How Can I Modify Non-Global Variables in Outer Scopes in Python?

Modifying Non-Global Variables in Outer Scope in Python

In Python, variables within a function typically belong to the local scope, unless explicitly declared as global. However, it is sometimes necessary to modify variables defined in an outer (enclosing) but non-global scope. This question explores how to achieve this.

Given the example code:

def A():
    b = 1
    def B():
        # Access to 'b' is possible here.
        print(b)
        # Direct modification of 'b' fails.
    B()
A()

The variable b in function B resides in a non-global, enclosing scope. Attempts to modify b directly result in an UnboundLocalError. The global keyword can't be used since b is not declared at the global level.

Python 3 Solution:

Nonlocal Scope (Python 3.x) can be used to solve this issue:

def A():
    b = 1
    def B():
        nonlocal b  # Nonlocal keyword
        b = 2
    B()
    print(b)  # Output: 2
A()

Python 2 Solution:

Mutable Objects (Python 2.x):

Instead of reassigning variables directly, use mutable objects (e.g., lists, dicts) and mutate their values:

def A():
    b = []
    def B():
        b.append(1)  # Mutation of 'b'
    B()
    B()
    print(b)  # Output: [1, 1]
A()

The above is the detailed content of How Can I Modify Non-Global Variables in Outer 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