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:
- Current function Scope
- Any peripheral scope (for example, other functions that contain the current function)
- 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.
- If the current scope variable already exists, its value will be replaced.
- 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()