How does Python access variables in the peripheral scope?

Source: Internet
Author: User

How does Python access variables in the peripheral scope?

When a variable is referenced in an expression, Python traverses various scopes in the following order to find the variable:

  1. Current function Scope
  2. Any peripheral scope (for example, other functions that contain the current function)
  3. Global scope, that is, the scope of the module where the code is located

If no variable is found in the preceding scope, a NameError exception is reported.

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

  1. If the current scope variable already exists, its value will be replaced.
  2. If it does not exist, it is considered to define a new variable in the current scope, rather than looking for a new variable in the peripheral scope.

Functions

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

Because the variables in helper are assigned values, the flag output is still True. I am used to static language such as c. This design is initially confusing, but it can effectively prevent local variables from polluting the environment outside the function.

There are always various requirements. Some programmers must want to access the peripheral scope when assigning values. If it is Python2, he can do this.

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

Use flag [0] As a read operation to generate a variable reference and find the flag in the peripheral scope. In this case, assign the Value flag [0] = False to avoid the new variable definition.

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

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

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.