Python import Mechanism

Source: Internet
Author: User

This article describes the import mechanism of Python, which is helpful for understanding the operating mechanism of Python!

1. Standard import:

All modules loaded to the memory in Python are placed in sys. modules. When importing a module, the system first checks whether the module has been loaded in the list, if it is loaded, the module name is added to the Local namespace of the module that is calling import. If not loaded. find the module file in the path directory according to the module name. The module can be py, pyc, or pyd. Find the module and load it into the memory and add it to sys. modules, and import the name to the current Local namespace.

A module is not loaded repeatedly. Multiple different modules can use import to introduce the same module to their Local namespace. In fact, there is only one PyModuleObject object. Here is a problem that is easy to ignore: import can only import modules, but cannot import objects (classes, functions, variables, and so on) in modules ). For example, there is A function getName in module A (A. py). The other module cannot import getName to this module through import A. getName. It can only use from A import getName.

2. nested import:

1) sequential nesting

For example, this module imports A module (import A), A and B, and B modules can import other modules ......
Nesting is easy to understand. Note that the Local namespaces of each module are independent. For the above example, after this module is imported to module A, this module can only access module A, but cannot access module B and other modules. Although Module B has been loaded into the memory, if the access is made clear, import B in this module.

2) loop nesting

For example:

File [A. py]

from B import Dclass C:pass

File [B. py]

from A import Cclass D:pass

Why cannot I load D when executing?
You can change A. py to import B.
What's going on?

Robert Chen: This is related to the internal import mechanism of Python. Specifically, from B import D, Python is divided into several steps:
(1) Search for the symbol "B" in sys. modules"
(2) If symbol B exists, the module object corresponding to symbol B is obtained.
Obtain the object corresponding to the symbol "D" from _ dict _ in <modult B>. If "D" does not exist, an exception is thrown.
(3) If symbol B does not exist, a new module object <module B> is created. Note that the _ dict _ of the module object is empty.
Run the expression in B. py and fill in _ dict _ of <module B> __.
Obtain the object corresponding to "D" from _ dict _ of <module B>. If "D" does not exist, an exception is thrown.

The execution sequence of this example is as follows:

1. Execute. in py, from B import D is the execution python. py, so in sys. no <module B> exists in modules. The value is B first. py creates a module object (<module B>). Note that the created module object is empty and there is nothing in it. After this module object is created in Python, it will parse and execute B. py to fill in <module B> This _ dict __.
2. Execute B. in py, from A import C is executing B. in the process of py, check the sys. whether the module cache of modules already exists <module A>. Because <module A> is not cached yet, similar to this, Python internally uses. py creates A module object (<module A>), and then, similarly, runs. statement in py
3. Execute. in py, the <module B> object created in step 1st is already cached in sys. in modules, we get <module B> directly. However, note that from the whole process, we know that <module B> is still an empty object, there is nothing in it, so the operation to get the symbol "D" from this module will throw an exception. If this is only import B, because the "B" symbol already exists in sys. modules, no exception will be thrown.

ZQ: the diagram is as follows:

3. Package import

As long as there is a _ init _. py file under a folder, this folder can be seen as a package. The package import process is basically the same as that of the module, but the _ init _. py in the directory of the package will be executed when the package is imported, rather than the statements in the module. In addition, if only the package is imported, and the package's _ init _. py does not have any other initialization operations, the modules below this package will not be automatically imported.
For example:
The following package structure is available:
PA
| ---- _ Init _. py
| ---- Wave. py
| ---- PB1
| ---- _ Init _. py
| ---- Pbw.m.py
| ---- PBS
| ---- _ Init _. py
| ---- Pb2_m.py
There are the following programs:

import sysimport PA.wave              #1import PA.PB1                #2import PA.PB1.pb1_m as m1    #3import PA.PB2.pb2_m          #4PA.wave.getName()           #5m1.getName()                #6PA.PB.pb2_m.getName()       #7

1) after #1 is executed, sys. modules will have both paw.pa.wav e modules. In this case, you can call any class or function of PA.wav e. However, you cannot call any module under PA. PB1 (2. The Local database has the PA name.

2) After executing #2. PB1 load memory, sys. modules contains PA, PA.wav e, and PA. PB1 three modules, But PA. no modules in PB1 are automatically loaded into the memory. If PA is directly executed. PB1.pb1 _ m. getName () will cause an error because PA. pb1_m is not found in PB1. The current Local still only has the PA name, and there is no PA. PB1 name.

3) after executing #3, the PA. pb1_m under PB1 is loaded into memory, sys. modules contains paw.pa.wav e and PA. PB1, PA. PB1.pb1 _ m four modules, You can execute PA. PB1.pb1 _ m. getName. Because the as is used, in addition to the PA name in the Local file, m1 is added as the alias of PA. PB1.pb1 _ m.

4) after executing #4, the PA. PBS, PA. pb2.pbs _ m load memory, sys. modules contains paw.pa.wav e and PA. PB1, PA. PB1.pb1 _ m, PA. PBS, PA. six modules of pb2.pbs _ m. Currently, only PA and m1 are available in Local.
The following #5, #6, and #7 operations can be correctly run.

Note:If you want to import pa.pb1.pb?m=pa.wav e to PA. pb2.k2m, you can directly import it. It is best to use a clear import path, which is not recommended for relative import paths.

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.