Python import mechanism memo-module search path (SYS. Path), nested import, package Import

Source: Internet
Author: User
Tags python list

From: http://fanhaijun.com /? P = 1065

Module search path

The search path of the module is placed in the SYS. Path list. If the default SYS. path does not contain its own module or package path, you can dynamically add
(SYS. Path. apend. The following is how SYS. Path is added on Windows.

1. The first path of SYS. Path is usually the directory of the main module. Add an empty entry in the interaction environment, which corresponds to the current directory.

2. If the pythonpath environment variable exists, SYS. Path loads the directory specified by this variable.

3. We try to find Python home. If we set the pythonhome environment variable, we think this is Python.
Home,no, we use the directory where python.exe is located to find lib/OS. py to deduce Python home.

If we find the python home, the related sub-directories (Lib, Plat-win, Lib-TK, etc.) will use Python
Add home to SYS. Path, import (execute) lib/site. py, and add the site-specific directory and its package.

If we do not find Python
Home, add the entry of the registry software/Python/pythoncore/2.5/pythonpath to SYS. Path (HKLM and
Hkcu is added after merging), but the related sub-directories are not automatically added.

4. If we do not find Python
Home, and there is no pythonpath environment variable, and the pythonpath cannot be found in the registry, then the default relative path will be added (such as:./LIB ;.
/Plat-Win ).

Summary:

When running python.exe in the installed directory, first infer that python
Home. If pythonhome is found, the pythonpath in the registry is ignored; otherwise, the pythonpath in the registry is added.

If the pythonpath environment variable exists, SYS. path will certainly load the directory specified by this variable.

If python.exe is in another directory (different directories, such as embedding it into other programs through COM ),
Home will not be inferred, And the pythonpath of the Registry will be used.

If python.exe cannot find its main directory (pythonhome) and the Registry does not have pythonpath, it will be added to the default relative directory.

Standard import

All modules loaded to the memory in Python are placed in SYS. modules. When you import a module, the system first checks whether the module has been loaded in the list.
The module name is added to the local namespace of the module that is calling import. If it is not loaded, search for the module file according to the module name in the SYS. Path directory.
The block files can be py, PyC, and PYD. After finding the block file, load the module into the memory, add it to SYS. modules, and import the name to the current local namespace.

We can see that a module will not be loaded repeatedly. You can use import to import multiple modules to your local namespace.
There is only one pymoduleobject object.

It is easy to ignore. Import can only import modules, but cannot import objects (classes, functions, variables, and so on) in modules ). For example, a module A (A. py) has a function.
Getname. The other module cannot import getname to this module through import a. getname.
A. If you want to import only specific classes, functions, and variables, use from a import getname.

Nested Import

Nested import, which is divided into two situations: This module imports a module (Import
A), and an import statement in a will activate another Import action, such as import B, while Module B can import other modules.

This Nesting is easy to understand. Note that the local namespaces of each module are independent. Therefore, in the preceding example, the import
After a is complete, this module can only access module A and cannot access module B and other modules. Although Module B has been loaded into the memory, if you want to access it, you must explicitly import B in this module.

Another nesting method is to import B in module A and import B in Module B.
A. What will happen now? This is explained in detail by Robert Chen in the python list. The transcript is as follows:

[A. py] From B Import D Class C: Pass [B. py] from a import C Class
D: Pass

Why cannot I load D when executing?

You can change a. py to import B.

What's going on?

Robert tchen: 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.

    Obtains the object corresponding to the symbol "D" from _ dict _ of <Module B>. If "D" does not exist, an exception is thrown.

  3. If symbol B does not exist, a new module object <Module
    B> note: 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.

Therefore, the execution sequence of this example is as follows:

1. Execute from B Import D in A. py.

Because Python A. py is executed, there is no <Module
B> Yes. First, create a module object for B. py (<Module
B>). Note that the module object created at this time is empty and there is nothing in it. After this module object is created in Python, it will be parsed and executed B. py,
The purpose is to fill in the dict <Module B>.

2. Execute from a import C in B. py.

During execution of B. py, the system first checks whether the module cache contains <Module
A> now, because the cache has not been cached <Module
A>. Similarly, Python internally creates a module object for A. py (<Module
A>), and then, similarly, execute the statement in A. py.

3. Execute from B Import D in A. py again

At this time, because the created <Module B> object is already cached in SYS. modules at step 1, you can directly obtain the <Module
B>, but note that we know from the whole process that <Module
B> it is still an empty object, and there is nothing in it, so the operation to get the symbol "D" from this module will throw an exception. If only import
B. Because the "B" symbol already exists in SYS. modules, no exception is thrown.

The above explanation has been included by zoom. Quiet in the woodpecker
Now,
There is a picture in it. For more information, see.

Package (Package) Import

A package can be viewed as a set of modules. As long as a folder contains a _ init _. py file, this folder can be viewed as a package. Folder under the package
It can also be a package (sub-package ). Furthermore, multiple smaller packages can be aggregated into a larger package. The structure of the package facilitates class management and maintenance, and facilitates user use. For example
Sqlalchemy and others are all released to users in the form of packages.

The package and module are very similar. If you view the package type import sqlalchemy
Type (sqlalchemy), you can see that it is also <type
'Module'>. The path to be searched during the import package is also SYS. Path.

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 you just import the package,
The _ init _. py package does not have other Explicit initialization operations, so the modules below this package will not be automatically imported. For example:

Pa

-_ Init _. py

-Wave. py

-PB1

-_ Init _. py

-Pbw.m.py

-PBS

-_ Init _. py

-Pb2_m.py

_ Init _. py is empty. If the following programs exist:

  1. Import sys
  2. Import pa.wav e #1
  3. Import Pa. PB1 #2
  4. Import Pa. pb1.pb1 _ m as M1 #3
  5. Import Pa. pb2.pbs _ m #4
  6. Pa.wav E. getname () #5
  7. M1.getname () #6
  8. Pa. pb2.pbs _ M. getname () #7

When the execution period is 1, sys.moduleswill have the paw.pa.wave, and you can use any class or function of pa.wav E. But cannot be called
Any module under PA. PB1 (2. The local database has the PA name.

When the execution of ipv2, only the pa.pb1is loaded into the memory, sys.modulesthere will be three modules: paw.pa.wav E and Pa. PB1, but any of them under PA. PB1
The module is not automatically loaded into the memory. If Pa. pb1.pb1 _ M. getname () is directly executed, an error occurs because no pb1_m exists in PA. PB1. Current local
There is still only the name of Pa, and there is no name of PA. PB1.

When the execution is completed 3, The pbsmbs under pa.pb1will be loaded into the memory, and sys.moduleswill include paw.pa.wav E, Pa. PB1,
The PA. pb1.pb1 _ m module executes Pa. pb1.pb1 _ M. getname. Because the as is used, apart from the PA name in the current local
M1 is added as the alias of PA. pb1.pb1 _ m.

When the execution is completed, the pa.pb2?pa.pb2.pb2_mwill be loaded into the memory, and the sys.lesleswill include paw.pa.wav E, Pa. PB1,
Six modules are Pa. pb1.pb1 _ m, Pa. PBS, and Pa. pb2.k2m. Currently, only Pa and M1 are available in local.

The following #5, #6, and #7 operations can be correctly run.

NOTE: If pa.pb2.pb2_mwants to import pa.pb1.pb?m=pa.wav e, it can be directly successful. It is best to use a clear import path
It is not recommended to use 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.