Accessing Nonlocal Variables in Nested Function Scopes
In Python, nested function scopes provide access to enclosing scopes. However, attempting to modify a variable in an enclosing scope within a nested function can result in an UnboundLocalError.
To address this issue, you have several options:
1. Using the 'nonlocal' Keyword (Python 3 ):
For Python 3 and onwards, the nonlocal keyword allows you to rebind nonlocal variables within nested functions.
def outer():
ctr = 0
def inner():
nonlocal ctr
ctr = 1
inner()
2. Indirect Access via Lists (Python 2 and 3):
In both Python 2 and 3, you can use a list to hold the variable and increment it indirectly within the nested function.
ctr = [0]
def inner():
ctr[0] = 1
3. Using Global Variables (Not Recommended):
While using global can allow access to variables from enclosing scopes, it's generally discouraged due to potential conflicts and code readability issues.
def outer():
global ctr
ctr = 0
def inner():
ctr = 1
Choosing the appropriate solution depends on your specific Python version and the design considerations for your code.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3