How does Python access variables in a peripheral scope

  • 2020-05-10 18:23:22
  • OfStack

When a variable is referenced in an expression, Python traverses the scopes looking for it in the following order:

Current function scope Any peripheral scope (such as other functions that contain the current function) The global scope, which is the scope of the module where the code resides

If none of the variables are found in the above scope, an NameError exception is reported.

But when assigning values to variables, the rules are different.

If the current scoped variable already exists, its value is replaced. If it does not exist, it is treated as if the new variable is defined in the current scope, rather than looking for it in the outer scope.

The following functions


def function():
  flag = True
  def helper():
    flag = False
  helper()
  print flag

function()

Since the variable is assigned in helper, the output of flag is still True. Accustomed to statically typed languages like c, this design can be confusing at first, but it effectively prevents local variables from polluting the environment outside of functions.

The requirements are always varied, 1 there must be programmers who want to access the peripheral scope at assignment time. If it was Python2, he could do that


def function():
  flag = [True]
  def helper():
    flag[0] = False
  helper()
  print flag

function()

First, flag[0] is a read operation, which generates a variable reference, and flag is found in the outer scope. At this point, flag[0] = False will not define a new variable.

If it is Python3, you can use the nonlocal keyword.


def function():
  flag = True
  def helper():
    nonlocal flag
    flag = False
  helper()
  print flag

function()


Related articles: