Global versus nonlocal in python

  • 2020-04-02 14:24:28
  • OfStack

The order in which python references variables: local variables in the current scope - > Outer scope variable - > Global variable - in the current module > Python built-in variables

First, global

The global keyword is used to use global variables in functions or other local scopes. But you can also get rid of the global keyword without modifying global variables.


gcount = 0 def global_test():
    print (gcount)
   
def global_counter():
    global gcount
    gcount +=1
    return gcount
   
def global_counter_test():
    print(global_counter())
    print(global_counter())
    print(global_counter())

Second, the nonlocal

The nonlocal keyword is used to use outer (non-global) variables in functions or other scopes.


def make_counter():
    count = 0
    def counter():
        nonlocal count
        count += 1
        return count
    return counter
   
def make_counter_test():
  mc = make_counter()
  print(mc())
  print(mc())
  print(mc())

You can also use generator to implement a similar counter. As follows:


def counter_generator():
    count = 0
    while True:
        count += 1
        yield count
   
def counter_generator_test():
  # below is for python 3.x and works well
  citer = counter_generator().__iter__()
  i = 0
  while(i < 3) :
    print(citer.__next__())
    i+=1
 
def counter_generator_test2(): 
  #below code don't work
  #because next() function still suspends and cannot exit
  #it seems the iterator is generated every time.
  j = 0
  for iter in counter_generator():
    while(j < 3) :
      print(iter)
      j+=1


Related articles: