How Python accesses variables in the perimeter scope _python

Source: Internet
Author: User

When you reference a variable in an expression, Python iterates through the scopes in the following order, looking for the variable:

    1. Current function scope
    2. Any perimeter scope (such as other functions that contain the current function)
    3. Global scope, which is the scope of the module where the code resides

If no variables are found in the scope above, the Nameerror exception is reported.

However, when assigning values to variables, the rules vary.

    1. If the current scope variable already exists, its value is replaced.
    2. If it does not exist, it is considered to define a new variable in the current scope instead of looking for it in the perimeter scope.

The following functions

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

function ()

Because the variable in the helper is an assignment, the flag output is still True here. Accustomed to the C language, such as static type language, this design will initially be confused, but it can effectively prevent the local variable pollution functions outside the environment.

Requirements are always diverse, and there must be programmers who want to access the perimeter scope when assigned. If it's Python2, he can do it.

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

function ()

First Use flag[0] is read operation, produce a variable reference, look for the outer scope of the flag, then the assignment flag[0] = False will not be a new definition of the 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 ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.