In practical applications , We can Python A namespace in a language is understood as a container . Many identifiers can be placed in this container , Identifiers with the same name in different containers do not conflict with each other , They correspond to each other . stay Python In the program , Use namespaces to record the trace of variables . A namespace is a dictionary (Dictionary), Its key is the variable name , Its value is the value of the corresponding variable .
stay Python In the program , There are usually three namespaces available .
(1) Each function has its own namespace , This is called a local namespace , It records the variables of the function , Including parameters of functions and locally defined variables .
(2) Each module has its own namespace , This is called the global namespace , It records the variables of the module , Include function 、 class 、 Other imported modules 、 Module level variables and constants .
(3) There is also the built-in namespace , Any module can access it , It holds built-in functions and exceptions .
To understand Python The namespace of the language , First, you need to master the following three rules .
(1) assignment ( Including explicit assignment and implicit assignment ) Generate identifier , The location of the assignment determines the namespace of the identifier .
(2) Function definition ( Include def and lambda) Generate a new namespace .
(3) Python The order in which an identifier is searched is “LEGB”. So-called “LEGB”, Refer to Python In language 4 The abbreviation of the English name of the layer namespace , The details are as follows .
● Innermost 1 Layer is L (local), In a function definition , And the function definition is not included in this function .
● The first 2 layer E (enclosing functio), In a function definition , But this function also contains the definition of the function , Actually L Layer and the E Layers are only relative .
● The first 3 layer G (global) , Refers to the namespace of a module , That is to say, in one .py The identifier defined in the file , But not in a function .
● The first 4 layer B (builtin) , Refer to Pylo The namespace that the interpreter already has when it starts , The name builtin Because in Python The interpreter will load automatically when it starts __builtin__ modular , In this module list、str Wait for the built-in function to be in B In the namespace of the layer . Be careful : stay Python In the program , You can manage complex programs through modules , The functions with different functions are distributed in different modules , Functions and their global namespaces determine the values of global variables referenced in functions . The global namespace of a function is always the module that defines the function , Instead of calling the namespace of the function . therefore , The global variables referenced in a function are always the global variables defined in the function module .
For example, in the following example code , Demonstrates the process of the relationship between a function and its global namespace . Example files mo.py Is a module file , It defines the global weight change name And the function moo_fun(), And in the function moo_fun() Global variables are output in name Value . file mo.py The specific implementation code of is as follows .
name= "Moo Module" # Defining variables name The initial value of the
def moo_fun(): # Define methods moo fun()
print(' function moo_fun: ') # Print display text
print(' Variable name: ',name) # Print display variables name Value
Example files test.py It's a test file , Called module mo The method in moo_fun(). Global variables are also defined in this file name And the function bar(), And in the function bar() Global variables are output in name Value . Then call the functions defined in this module bar() And from the mo Functions imported from the module moo_fun(), Finally, it defines a function that is passed in and called as a parameter call_moo_fun(). Because the global variables referenced in the function are always the global variables defined in the function module , So the first call outputs the global variables in the current module name Value ; The second call is from mo Functions imported from the module moo_fun(), The output is in mo Global variables in the module name Value . Third call call_moo_fun() function , And take the mo Functions imported from the module moo_fun() Pass it as a parameter to make a call , Even if it is called inside a function , It still outputs the function moo_fun() Global variables in the module name Value . Example files test.py The specific implementation code of is as follows .
from mo import moo_fun # Call module mo The method in moo fun ()# Define global variables name
name='current module'
def bar(): # Defined function bar()
print (' Functions in the current module bar: ') # Print display text
print (' Variable name: ', name) # Print display variables name Value
def call_moo_fun (fun) : # Define methods cal1_moo_fun ()
fun ()
if __name__== '__main__': # Output the global variables in the current module name Value
bar()
print() # Call from mo Functions entered in the module moo_fun
moo_fun ()
print()
call_moo_fun (moo_fun)
After running the program , The first 1 The second output is the global variables in the current module name Value ’current module’, The first 2 The second output is mo Global variables in the module name Value “Moo Module”, The first 3 The second output is still mo Global variables in the module name Value “Moo Module”. After execution, it will output :
stay Python In the program , When a line of code uses variables x The value of , It will look for this variable in all available namespaces , Search in the order shown below .
(1) Local namespace : The method of the current function or class . If the function defines a local variable x, Or a parameter x,Python The program will use it , And then stop searching .
(2) Global namespace : Specific to the current module . If the module defines a name called x The variable of , A function or class ,Python Will use it and stop searching .
(3) Built in namespace : It's global to every module . As a last resort ,Python It will be assumed that x It's a built-in function or variable .
(4) If Python Cannot find... In the above namespace x, It will discard the search and raise a NameError abnormal , for example NameError: name ‘aa’ is not defined.
stay Python In the program , The search order of nested function namespaces is special , The details are as follows .
(1) First in the current ( Nested or lambda) Search in the namespace of the function
(2) Then search in the namespace of the parent function .
(3) Then search the module namespace .
(4) Finally, search in the built-in namespace .
For example, in the following example code , Demonstrates the process of finding nested function namespaces .
info="2024 The host of the Olympic Games :" # Define the initial value of the global variable
def func_father (country): # Define the embedding function func_father()
def func_son(area): # Here city Variable , Overriding the parent function city Get heavier
city=" In Paris, "
print(info + country + city + area)
city=" Los Angeles "
func_son(" Platform area "); # Call internal function
func_father(" The French ")
In the example code above ,info In the global namespace ,country In the namespace of the parent function ,city and area In the namespace of your own function . After execution, it will output :
stay Python In the program , Create different namespaces at different times , These namespaces have different lifetimes . The details are as follows .
(1) The built-in namespace is in Python Created when the interpreter starts , It will be kept forever , It won't be deleted .
(2) The global namespace of a module is created when the module definition is read in , Usually, the module namespace will also be saved until the interpreter exits .
(3) A local namespace is created when a function is called. It is deleted when a function returns a result or throws an exception . Each recursively called function has its own namespace .
Python Language has a special feature of its own , Its assignment is always in the innermost scope . Assignment does not copy data , Just bind names to objects . The same is true for delete operations , for example “del y” Just remove the name from the namespace of the local scope “y” nothing more . As a matter of fact , All operations that introduce new names act on the local scope . Take a look at the demo code below , Because when creating namespaces ,Python Will check the code and fill in the local namespace . And add it to the local namespace . When the function executes
Python Before running that line of code , I found out right i When the assignment line of ,Python The interpreter thinks that i In the local namespace , But it's not worth it , So there will be errors .
i=1
def func2():
i=i+1
func2();
Error in execution result :
stay Python When accessing a namespace in a program , Different namespaces are accessed in different ways , The details are as follows .
(1) Local namespace .
stay Python Built in functions can be used in programs locals() To access local namespaces . For example, in the following example naming code , Demonstrates the use of built-in functions locals() To access the local namespace .
The specific implementation code is as follows .
def funcl(i,str): # Defined function func1 ()
X=1234 # Defining variables x The value of is 12345
print(locals()) # Access local namespaces
funcl(1,"firs")
After execution, it will output :
(2) overall situation ( Module level ) Namespace .
stay Python In the program , You can use built-in functions globals() To access the global ( Module level ) Namespace .
For example, in the following example code , Demonstrates the use of built-in functions globals() To access the global namespace .
import copy # Import copy modular
from copy import deepcopy # Import deepcopy
gstr = "global string" # Defining variables gstr
def funcl(i,info): # Defined function func1 ()
x = 12345
print(locals()) # Access local namespaces
funcl(1,"first")
if __name__=="__main__":
print("the current scope's global variablest:")
dictionary=globals() # Access global ( Module level ) Namespace
print (dictionary)
The effect after execution is shown in the figure below , Here we need to pay attention to , Some output results in the execution effect will vary depending on the user's test environment .
Be careful : It can be seen from the above execution effect , Module namespaces contain more than module level variables and constants , It also includes all the functions and classes defined in the module . in addition to , It also includes anything imported into the module . You can also see , Built in naming is also included in a module , It is called __builtins__ . When using import module when , The module itself is imported , But it maintains its own namespace , That's why you need to use the module name to access its functions or properties module.fumction Why . But when used from module import function when , It is actually importing the specified functions and attributes from another module into the namespace , This is why we can access them directly without referring to the module from which they came . In the use of globals Function time , Will really see all this happen .
stay Python In the program , Use built-in functions locals() and globals() Is different . among locals Is read-only , and globals Is not read-only . For example, in the following example code , Demonstrated locals And globals The difference between .
def func1 (i,info) : # Defined function func1 ()
x = 41 # Definition x The initial value of the
print (locals()) # Access local namespaces
locals()["A countries "] = 23 #locals Is read-only
print ("A countries =",x)
y=55 # Definition y The initial value of the
func1 (1,"first")
globals() ["B countries "]= 34 #globals It's not read-only
print("B countries =",y)
After execution, it will output :
stay Python In the program ,locals It doesn't actually return the local namespace , It returns a copy . So changing it has no effect on the value of the variable in the local namespace . and globals Returns the actual global namespace , Not a copy . So for globals Returned dictionary Any changes to the will directly affect the global variables .
運行Python程序出現“RuntimeError: ‘cr
本文繼續探究學Pytorch時,涉及到的python底層的一