The nature of the Python namespace

Source: Internet
Author: User

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 namespaceis 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 orderWhen 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. Nested functions: 1, first in the current (nested or lambda) function of the namespace search 2, then the parent function in the namespace search 3, followed by the module namespace Search 4, and finally in the built-in namespace search example:
1info ="Adress:"2 defFunc_father (country):3     defFunc_son (area):4city="Shanghai" #the city variable here, which overrides the city variable of the parent function5         Print(Info + country + City +Area )6City ="Beijing"7     #Calling intrinsic functions8Func_son ("Chaoyang");9  TenFunc_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 namespaceDifferent 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:
1 i=12def  Func2 ():3     i=i+14  5func2 (); 6 # error: 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.

1 def func3 (): 2 y=1233del  y4print(y)56 func3 () 7 # error: unboundlocalerror:local variable ' y ' referenced before assignment 8 # after removing the "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:
1 def func1 (i, str): 2     x = 123453     print(Locals ())4  5"First ")

Output: {' str ': ' First ', ' X ': 12345, ' I ': 1}

2. Global (module level) namespaces can be accessed through Globals () bif. Example:
1 " "Created on 2013-5-26" "2  3 ImportCopy4  fromCopyImportdeepcopy5  6Gstr ="Global String"7  8 deffunc1 (I, info):9x = 12345Ten     Print(Locals ()) One   AFunc1 (1," First") -   - if __name__=="__main__": the     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 ': <module ' copy ' from ' d:\\python33\\lib\\copy.py ';   ' __builtins__ ': <module ' builtins ' (built-in) >,  ' gstr ': ' Global string ',  ' dictionary ': {...},    ' func1 ': <function func1 at 0x01c6c540>,  ' deepcopy ': <function deepcopy at 0x01db28a0>}  summary 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 GlobalsLocals is read-only, Globals is not an example:
1 deffunc1 (I, info):2x = 123453     Print(Locals ())4Locals () ["x"]= 67895     Print("x=", X)6  7y=543218Func1 (1," First")9Globals () ["y"]= 9876Ten Print("y=", y)

Output:

{' I ': 1, ' x ': 12345, ' info ': ' First '}x= 12345y= 9876 explanation: Locals does not actually 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.

The nature of the Python namespace

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.