Python's namespace is something the Python program ape must understand, and learning about the Python namespace will allow us to essentially master some of the trivial rules in Python.
Next I will reveal the nature of the Python namespace in four parts: first, the definition of the namespace, the search order of the namespace, the life cycle of the namespace, and the lifetime of the namespaces. Access namespaces through locals () and Globals () BIF
The focus is on part fourth, and we'll look at the contents of the namespace in this section.
First, the name space
Python uses something called a namespace to record the trajectory of a variable. A namespace is a dictionary (dictionary) whose key is the variable name, and its value is the value of those variables.
A namespace is a mapping from names to objects. Most namespaces is currently implemented as Python dictionaries.
There are several namespaces available in any one of the Python programs.
1. Each function has its own namespace, called the local namespace, which records the variables of the function, including the parameters of the function and locally defined variables.
2, each module has its own namespace, called the global namespace, which records the variables of the module, including functions, classes, other imported modules, module-level variables and constants.
3, there is a built-in namespace, any module can access it, it holds built-in functions and exceptions.
Second, namespace lookup order
When a line of code is going to use the value of the variable x, Python will go to all available namespaces to find the variable, in the following order:
1. Local namespace: Refers to the method of the current function or class. If the function defines a local variable x, or a parameter X,python will use it, then stop the search.
2. Global namespace: Refers to the current module. If the module defines a variable called X, a function or a class, Python will use it and then stop the search.
3. Built-in namespaces: All are global to each module. As a final attempt, Python will assume that X is a built-in function or variable.
4. If Python cannot find X in these namespaces, it will discard the lookup and throw a Nameerror exception, such as Nameerror:name ' AA ' is not defined.
The case of nested functions:
1. First search in the namespace of the current (nested or lambda) function
2, then search in the namespace of the parent function
3, followed by the module namespace search
4. Finally search in the built-in namespace
Example:
info = "Adress:" Def func_father (country): def func_son (area): city= "Shanghai" #此处的city变量, the city variable that overrides the parent function Print (info + country + City + area) City = "Beijing" #调用内部函数 Func_son ("Chaoyang"); Func_father ("China")
Output: Adress:china Shanghai Chaoyang
In the example above, info is in the global namespace, country in the namespace of the parent function, and city and area are in the namespace of their own function
Third, the life cycle of the namespace
Different namespaces are created at different times and have different lifetimes.
1. Built-in namespaces are created at the start of the Python interpreter and are retained and not deleted.
2. The module's global namespace is created when the module definition is read-only, and the module namespace is usually saved until the interpreter exits.
3, when the function is called to create a local namespace, when the function returns the result or throws an exception, is deleted. Each function that is called recursively has its own namespace.
One of the special things about Python is that its assignment is always in the innermost scope. The assignment does not copy the data-just binds the name to the object. Deletion is also true: "Del y" simply removes the named Y from the local scope's namespace. In fact, all operations that introduce new names are used for local scopes.
Example:
I=1
Def FUNC2 ():
I=i+1
Func2 ();
#错误: unboundlocalerror:local variable ' i ' referenced before assignment
Because the namespace is created, Python examines the code and populates the local namespace. Before Python runs that line of code, it finds the assignment to I and adds it to the local namespace. When the function executes, the Python interpreter thinks I is in the local namespace but has no value, so it generates an error.
Def func3 ():
Y=123
Del y
Print (y)
FUNC3 ()
#错误: unboundlocalerror:local variable ' y ' referenced before assignment
After #去掉 "Del y" statement, it runs normally
Iv. access to namespaces
1, the local namespace can be locals () bif to access.
Locals returns the dictionary of a name/value pair. The dictionary key is a variable name in the form of a string, and the value of dictionary is the actual value of the variable.
Example:
def func1 (i, str):
x = 12345
Print (Locals ())
Func1 (1, "first")
Output: {' str ': ' First ', ' X ': 12345, ' I ': 1}
2. Global (module level) namespaces can be accessed through Globals () bif.
Example:
"' Created on 2013-5-26 '" import copyfrom copy import deepcopy gstr = "Global string" def func1 (i, info):
x = 12345 print (Locals ()) func1 (1, "first") if __name__ = = "__main__": print ("The current scope ' s Global variables: ") dictionary=globals () print (dictionary)
Output: (I give the person to change the line, change the order, add the color of the statement below the key description)
{
' __name__ ': ' __main__ ',
' __doc__ ': ' Created on 2013-5-26 ',
' __package__ ': None,
' __cached__ ': None,
' __file__ ': ' e:\\workspacep\\test1\\src\\base\\test1.py ',
' __loader__ ': <_frozen_importlib. Sourcefileloader object at 0x01c702d0>
' Copy ': ,
' __builtins__ ': ,
' Gstr ': ' Global string ',
' dictionary ': {...},
' Func1 ': ,
' Deepcopy ':
}
Summarize
1. The module namespace includes not only module-level variables and constants, but also all functions and classes defined in the module. In addition, it includes anything that is imported into the module.
2, we see that the built-in naming is also included in a module, which is called __builtin__.
3. Recall the difference between the From module import and the import module.
With the import module, the module itself is imported, but it maintains its own namespace, which is why you need to use the module name to access its functions or properties: The reason for the module.function.
But using the From module import function actually imports the specified functions and properties into your own namespace from another module, which is why you can access them directly without referencing the modules from which they originate. Using the Globals function, you will really see all this happening, see the red output statement above.
3. An important difference between locals and globals
Locals is read-only, Globals is not
Example:
def func1 (I, info): x = 12345 print (Locals ()) locals () ["X"]= 6789 print ("x=", x) y=54321func1 (1, "First") globals () ["Y"]= 9876print ("y=", y)
Output:
{' I ': 1, ' x ': 12345, ' info ': ' First '}
x= 12345
y= 9876
Explain:
Locals actually does not return a local namespace, it returns a copy. So changing it has no effect on the value of the variable in the local namespace.
Globals returns the actual global namespace, not a copy. Therefore, any changes to the dictionary returned by globals will directly affect the global variables.