Home >Backend Development >Python Tutorial >Introduction to the declaration and parsing of keywords nonlocal and global in Python
This articlePython contains relevant information on the declaration and analysis of the keywords nonlocal and global. The article introduces it in very detail. I believe it has certain reference value for everyone. Friends who need it can come together below. Let's see.
1. Global and nonlocal declarations in Python
The following code
a = 10 def foo(): a = 100
The result a of executing foo() is still the assignment to the
variable
function, the variable is always bound to The local namespace of this function, this behavior can be changed using the global statement.
>>> a 10 >>> def foo(): ... global a ... a = 100 ... >>> a 10 >>> foo() >>> a 100
When parsing a name, first check the local scope, and then check the scope defined by the external nested function layer by layer from the inside out. If it cannot be found, Search the global command space and built-in namespace.
Although you can look up variables layer by layer, but! ..python2 only supports the innermost scope (local variables) and the global command space (gloabl), which means internal functions Local variables defined in external functions cannot be reassigned. For example, the following code does not work.
def countdown(start): n = start def decrement(): n -= 1
In python2, the solution can be to modify The value is placed in a list or dictionary. In python3, you can use the nonlocal statement to complete the modification
def countdown(start): n = start def decrement(): nonlocal n n -= 1
2. Python nonlocal and global keywords Parsing
nonlocal
First of all, it is necessary to make it clear that the nonlocal keyword is defined in the closure. Please look at the following code:
x = 0 def outer(): x = 1 def inner(): x = 2 print("inner:", x) inner() print("outer:", x) outer() print("global:", x)
Result
# inner: 2 # outer: 1 # global: 0
Now, add the nonlocal keyword to the closure to declare it :
x = 0 def outer(): x = 1 def inner(): nonlocal x x = 2 print("inner:", x) inner() print("outer:", x) outer() print("global:", x)
Result
##
# inner: 2 # outer: 2 # global: 0Do you see the difference? This is a function nested inside a function. When using nonlocal, it is declared that the variable is not only valid in the nested function inner(), but is valid in the entire large function.
Still the same, look at an example:
x = 0 def outer(): x = 1 def inner(): global x x = 2 print("inner:", x) inner() print("outer:", x) outer() print("global:", x)
# inner: 2 # outer: 1 # global: 2
The above is the detailed content of Introduction to the declaration and parsing of keywords nonlocal and global in Python. For more information, please follow other related articles on the PHP Chinese website!