Understanding "nonlocal" in Python 3
Unlike traditional languages, Python allows nested functions to access variables defined in their outer scopes. However, accessing variables that are not declared within the nested function (i.e., non-local variables) can lead to unexpected behavior.
The "nonlocal" Keyword
In Python 3, the "nonlocal" keyword allows you to modify variables declared in an outer scope from within a nested function. By using "nonlocal", you declare that the variable you are modifying is non-local and belongs to an outer scope.
How "nonlocal" Works
Consider the following code without using "nonlocal":
x = 0 def outer(): x = 1 def inner(): x = 2 print("inner:", x) inner() print("outer:", x) outer() print("global:", x)
Output:
inner: 2 outer: 1 global: 0
In this example, the variable x in the inner function shadows the outer function's variable x, resulting in the value 2 being assigned to x within the inner function. The outer function's variable x is unaffected.
Using "nonlocal"
To modify the outer function's variable x from the inner function, we can use "nonlocal" as follows:
x = 0 def outer(): x = 1 def inner(): nonlocal x x = 2 print("inner:", x) inner() print("outer:", x) outer() print("global:", x)
Output:
inner: 2 outer: 2 global: 0
In this case, the "nonlocal" keyword allows the inner function to access and modify the outer function's variable x. As a result, the value of x in the outer function is changed to 2.
Comparison to "global"
Unlike "nonlocal," the "global" keyword refers to a variable that belongs to the global scope. Using "global" would bind the variable in the inner function to the global variable, regardless of the presence of other local variables with the same name:
x = 0 def outer(): x = 1 def inner(): global x x = 2 print("inner:", x) inner() print("outer:", x) outer() print("global:", x)
Output:
inner: 2 outer: 1 global: 2
Therefore, "nonlocal" should be used when you want to modify a variable declared in an outer scope, while "global" should be used when accessing a variable from the global scope.
The above is the detailed content of How Does Python's `nonlocal` Keyword Differ from `global` in Modifying Variables?. For more information, please follow other related articles on the PHP Chinese website!