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()
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
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]
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!