Python namespace instance parsing

Source: Internet
Author: User
The Python namespace is something that Python programmers must understand, in essence, we will master some trivial rules in Python. The Python namespace is something that Python programmers must understand and learn about Python namespaces, in essence, we will master some trivial rules in Python.

Next, I will reveal the essence of the Python namespace in four parts: 1. Namespace Definition; 2. namespace search sequence; 3. namespace lifecycle; 4. access the namespace through locals () and globals () BIF

The focus is on the fourth part, where we will observe the namespace content.

I. namespace

Python uses something called a namespace to record the trajectory of a variable. A namespace is a dictionary. its 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 are currently implemented as Python dictionaries.


There are several namespaces available in any part of a Python program.

1. each function has its own namespace, called a local namespace. it records function variables, including function parameters and locally defined variables.

2. Each module has its own namespace, which is called a global namespace. it records module variables, including functions, classes, other imported modules, module-level variables, and constants.

3. there is also a built-in namespace that can be accessed by any module. it stores built-in functions and exceptions.


II. namespace search sequence

When a line of code uses the value of variable x, Python searches for variables in all available namespaces in the following order:

1. local namespace: it refers to the method of the current function or class. If a function defines a local variable x or a parameter x, Python uses it and then stops searching.

2. global namespace: specifies the current module. If the module defines a variable, function, or class named x, Python uses it and then stops searching.

3. built-in namespace: Global for each module. As a final attempt, Python assumes that x is a built-in function or variable.

4. if Python cannot find x in these namespaces, it will discard the lookup and raise a NameError exception, for example, NameError: name 'A' is not defined.


Nested functions:

1. search in the namespace of the current (nested or lambda) function

2. search in the namespace of the parent function.

3. search in the module namespace

4. finally, search in the built-in namespace


Example:

Info = "Adress:" def func_father (country): def func_son (area): city = "Shanghai" # The city variable here, the print (info + country + city + area) city = "Beijing" # calls the internal function func_son ("ChaoYang"); func_father ("China ")


Output: Adress: China Shanghai ChaoYang

In the above example, info is in the global namespace, country is in the namespace of the parent function, and city and area are in the namespace of the own function.



III. lifecycle of a namespace

Different namespaces are created at different times and have different lifetime.

1. the built-in namespace will be retained and will not be deleted when it is created at the startup of the Python interpreter.

2. the global namespace of the module is created when the module definition is read. Generally, the module namespace is saved to the interpreter and exited.

3. when a function is called, a local namespace is created and deleted when the function returns results or throws an exception. Each recursive function has its own namespace.


A special feature of Python is that its value assignment operation is always at the innermost layer of scope. The value assignment does not copy data-it only binds the name to the object. Also, delete: "del y" only deletes the name y from the namespace in the local scope. In fact, all operations that introduce new names apply to local scopes.

Example:

I = 1

Def func2 ():

I = I + 1


Func2 ();

# Error: UnboundLocalError: local variable 'I' referenced before assignment

When creating a namespace, python checks the code and fills in the local namespace. Before running the code in python, I was assigned a value and added it to a local namespace. When a function is executed, the python interpreter considers that I is in a local namespace but has no value, so an error occurs.

Def func3 ():

Y = 123

Del y

Print (y)

Func3 ()

# Error: UnboundLocalError: local variable 'Y' referenced before assignment

# Run normally after removing the "del y" statement


IV. namespace access

1. the local namespace can be accessed by locals () BIF.

Locals returns a name/value pair's dictionary. The key of this dictionary is the 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. the global (module-level) namespace 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 replaced the line feed and the order manually. the color-adding statements are described below)

{

'_ 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 ':{...},

'Function1 ': ,

'Depopcopy ':

}


Summary

1. the module namespace contains not only module-level variables and constants, but also all functions and classes defined in the module. In addition, it includes anything imported into the module.

2. we can see that the built-in name is also included in a module, which is called _ builtin __.

3. think about the differences between from module import and import module.

When using 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 function or attribute: module. function.

However, using the from module import function actually imports the specified functions and attributes into your own namespace from another module, this is why you can directly access them without referencing the modules from which they are sourced. Using the globals function, you can see exactly what happened. See the above Red output statement.


3. an important difference between locals and globals

Locals is read-only and 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

Explanation:

Locals does not actually return a local namespace. It returns a copy. Therefore, modifying it does not affect the variable values in the local namespace.

Globals returns the actual global namespace instead of a copy. Therefore, any change to the dictionary returned by globals will directly affect the global variable.

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.