In-depth understanding of Python variable scope

Features

The scope of python is static, and the position where the variable name is assigned in the source code determines the scope of the variable that can be accessed. That is, the scope of a Python variable is determined by the location of the variable in the source code. Not all statement blocks in Python have scope. Only when variables are defined in Module, Class, and def, will there be the concept of scope.

1. Variables inside the function cannot be accessed outside the function

def func():
 variable =100print(variable)print(variable) # name 'variable' is not defined

2. Variables (scalar) in the upper layer of the function can only be read, cannot be defined again, and initialized

def counter1():
 n =0
 def compute():
 n = n +1 #n is a scalar (numerical value, string, floating-point number), the Python program will be,And modify this variable.Then python will think it is a local variable,And because there is no definition and assignment of n in the function, an error is reported
 # y = n +1 #Change to y and it's okay
 # return y
 return n
 return compute
variable =300
def test_scopt():print(variable) #At this time, the local variable variable is called and is not bound to a memory object(No definition and initialization, that is, no assignment). Essentially the LEGB rule
 variable =200 #Because here, it was called once before, so variable becomes a local variable
 # print(variable) #It’s okay to write below, because variable is a new local variable, not redefined, but not bound
test_scopt()

The module code in Python is not pre-compiled before being executed, but the function body code in the module is pre-compiled before running, so no matter where the variable name binding occurs in the scope, it can be compiled The device knows. Although Python is a statically scoped language, variable name lookup occurs dynamically, and scope problems will not be discovered until the program is running.

3. The values in compound variables such as list and dict can be changed by reference

def counter():
 n =[0]
 def compute():
 n[0]+=1 #The first value in n is changed, not n
 return n[0]return compute

func =counter()func() # 1func() # 2func() # 3

**4. global declares global variables. If you want to modify the global variables locally, you need to declare the global variables locally **

def counter1():
 n =0
 def compute():
 global n #If you want to modify the global variable locally, you need to declare the global variable locally,But there will be an error here, because there is no global variable n
 n +=1return n
 return compute

# right
def counter1():
 global n
 n =0
 def compute():
 global n
 n +=1return n
 return compute

5. The nonlocal keyword is used to use outer (non-global) variables in functions or other scopes

def make_counter():
 count =0
 def counter():
 nonlocal count #Use outer non-global variables
 count +=1return count
 return counter

Type of scope

In Python, when using a variable, it is not strictly required to declare it in advance, but before it is actually used, it must be bound to a memory object (defined, assigned); the binding of this variable name will be Introduce new variables in the current scope while shielding variables with the same name in the outer scope.

L(local) local scope

Local variables: included in the statement block defined by the def keyword, that is, variables defined in the function. A new local scope is created every time the function is called. There is also recursion in Python, that is, when you call yourself, each call will create a new local namespace. Variable declarations inside the function, unless they are specifically declared as global variables, default to local variables. In some cases, global variables need to be defined inside the function. At this time, you can use the global keyword to declare the scope of the variable as global. The local variable scope is like a stack, it only exists temporarily, depending on whether the function that created the local scope is active. Therefore, it is generally recommended to define as few global variables as possible, because global variables will always exist during the running of the module file and occupy memory space.
Note: If you need to assign a value to a global variable inside the function, you need to declare the variable as a global variable through the global statement inside the function.

E (enclosing) nested scope

E is also contained in the def keyword, E and L are relative, and E is also L relative to higher-level functions. The difference with L is that, for a function, L is the local scope defined in the function, and E is the local scope defined in the parent function of the function. Mainly to achieve Python closures, and increased implementation.

G(global) global scope

That is, for variables defined in the module hierarchy, each module is a global scope. In other words, the variables declared at the top level of the module file have global scope. From the outside, the global variables of the module are the attributes of a module object.
Note: The scope of the global scope is limited to a single module file

B (built-in) built-in scope

Variables defined in fixed modules in the system, such as variables predefined in the builtin module.

Scope chain: LEGB rule of variable name resolution

Search priority of variable names: local scope, nested scope, global scope, built-in scope
LEGB rule: When an undetermined variable name is used in a function, Python will search 4 scopes in sequence according to the priority to determine the meaning of the variable name. The local scope (L) is searched first, followed by the nested scope (E) of the def or lambda function in the upper nested structure, then the global scope (G), and finally the built-in scope (B). According to this search principle, stop at the first place found. If it is not found, a NameError will be raised.

example 1

name ="lzl"

def f1():print(name)

def f2():
 name ="eric"f1()f2() #Before the function is executed, the scope chain has been formed, at this time f1()The upper level should be name='lzl'

example 2

def scope_test():
 def do_local():
 spam ="local spam" #This function defines another spam string variable, and the life cycle is only in this function. Here spam and outer spam are two variables, if you write spam= spam +"Local spam" will report an error
 def do_nonlocal():
 nonlocal spam  #Use the outer spam variable test spam
 spam ="nonlocal spam"
 def do_global():
 global spam
 spam ="global spam"
 spam ="test spam"do_local()print("After local assignmanent:", spam) # test spam
 do_nonlocal()print("After nonlocal assignment:",spam) # nonlocal spam
 do_global()print("After global assignment:",spam) # nonlocal spam ????First look for local variables, the local variables found are already in do_nonlocal()The inside has changed so the output is nonlocal spam

scope_test()print("In global scope:",spam) # global spam

Recommended Posts

In-depth understanding of Python variable scope
In-depth understanding of python list (LIST)
Deep understanding of Python multithreading
What is Python variable scope
Understanding the meaning of rb in python
What is the scope of python variables
7 features of Python3.9
Basics of Python syntax
Basic syntax of Python
Basic knowledge of Python (1)
Prettytable module of python
09. Common modules of Python3
Consolidate the foundation of Python (4)
Consolidate the foundation of Python(7)
Subscripts of tuples in Python
Python analysis of wav files
Consolidate the foundation of Python(6)
Python parsing variable length structure
Analysis of JS of Python crawler
python king of glory wallpaper
Consolidate the foundation of Python(5)
Python implementation of gomoku program
Analysis of Python Sandbox Escape
Some new features of Python 3.10
Analysis of Python object-oriented programming
Python version of OpenCV installation
9 feature engineering techniques of Python
matplotlib of python drawing module
Python method of parameter passing
Consolidate the foundation of Python (3)
Collection of Python Common Modules