The declaration and parsing of the keywords nonlocal and global in Python

  • 2020-05-27 05:56:02
  • OfStack

1. global and nonlocal declarations in Python

The following code


a = 10 
 
def foo(): 
 a = 100 

When foo() is executed, a is still 10

An assignment to a variable in a function that is always bound to the function's local namespace, which can be changed using the global statement.


>>> a 
10 
>>> def foo(): 
...  global a 
...  a = 100 
... 
>>> a 
10 
>>> foo() 
>>> a 
100 

The local scope is checked first when the name is resolved, and then the scope defined by the external nested function is checked by the inner one layer, such as the search global command space and the built-in namespace cannot be found.

Although you can look out (up) for variables layer by layer, but! . python2 only supports the innermost scope (local variables) and the global command space (gloabl), which means that internal functions cannot re-assign local variables defined in external functions. For example, the following code does not work


def countdown(start): 
 n = start 
 def decrement(): 
  n -= 1 

In python2, the solution can be to put the modified values into a list or dictionary, and in python3, the modification can be done using the nonlocal declaration


def countdown(start): 
 n = start 
 def decrement(): 
  nonlocal n 
  n -= 1 

2. Python nonlocal and global keyword parsing

nonlocal

First, make it clear that the nonlocal keyword is defined inside a closure. See the following code:


x = 0
def outer():
 x = 1
 def inner():
  x = 2
  print("inner:", x)

 inner()
 print("outer:", x)

outer()
print("global:", x)

The results of


# inner: 2
# outer: 1
# global: 0

Now, add the nonlocal keyword to the closure to declare:


x = 0
def outer():
 x = 1
 def inner():
  nonlocal x
  x = 2
  print("inner:", x)

 inner()
 print("outer:", x)

outer()
print("global:", x)

The results of


# inner: 2
# outer: 2
# global: 0

See the difference? This is one function and one function inside of it. When nonlocal is used, the variable is declared not only in the nested function inner ()
It's going to work, but it's going to work for the whole big function.

global

Let's 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)

The results of


# inner: 2
# outer: 1
# global: 2

global works on variables in the environment as a whole, not on variables in a function class.

conclusion


Related articles: