When you reference a variable in an expression, Python iterates through the scopes in the following order, looking for the variable:
- Current function scope
- Any perimeter scope (such as other functions that contain the current function)
- 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.
- If the current scope variable already exists, its value is replaced.
- 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 ()