The Power of "nonlocal" in Python 3
In Python programming, variables can be classified according to their scope:
However, sometimes you need to bridge the gap between these scopes. This is where the "nonlocal" keyword comes into play.
Understanding "nonlocal"
"nonlocal" is used in Python 3 to declare a variable that exists in a broader scope but is not declared as global. It allows you to access and modify variables from enclosed functions without affecting the global variables with the same name.
Impact of "nonlocal"
To illustrate the difference, consider the following example without "nonlocal":
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Output:
1 2 3 |
|
In this case, the variable x within the inner() function is considered a new local variable, independent from the x in the outer() function and the global x.
Now, let's modify the code using "nonlocal":
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
Output:
1 2 3 |
|
In this scenario, the "nonlocal" keyword allows the x variable within the inner() function to reference and modify the x variable in the outer() function. The modifications made within the inner() function persist in the outer() function.
Difference from "global"
"nonlocal" differs from the "global" keyword in that it allows access and modification of variables from enclosed scopes, while "global" accesses and modifies variables from the truly global scope.
Using "global" in the above example would result in the following output:
1 2 3 |
|
In this case, the x variable within the inner() function would be bound to the global x and any changes would affect the value of the global variable, rather than the one in the outer() function.
Conclusion
"nonlocal" provides a powerful mechanism for accessing and modifying variables from enclosed scopes in Python 3. It allows you to avoid the pitfalls of modifying global variables within nested functions and maintain a more organized and modular code structure.
The above is the detailed content of How Does Python's `nonlocal` Keyword Differ from `global` in Nested Function Scope?. For more information, please follow other related articles on the PHP Chinese website!