Python Learning (17th) -- Import Mechanism

Source: Internet
Author: User
Tags python list

The more code you find, the more messy the import. You can only manage the module import.

Module search path

The search path of the module is placed in SYS. in the path list, if the default sys. the path does not contain its own module or package path. You can add it dynamically (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 the python home environment variable is set, we think this is Python home. if no, we use the directory where python.exe is located to find lib/OS. py to deduce Python home. If we find Python home, the related sub-directories (Lib, Plat-win, Lib-TK, etc.) will be added to SYS Based on Python home. path, and import (execute) lib/site. PY to add the site-specific directory and Its packages. If we do not find Python
Home, add the entry of the registry software/Python/pythoncore/2.5/pythonpath to SYS. Path (after merging HKLM and hkcu), but the related subdirectories are not automatically added.

4. If Python home is not found, and the Environment Variable pythonpath is not found in the Registry, the default relative path will be added (for example :. /LIB ;. /Plat-Win ).

Summary:

When running python.exe in the installed directory, first infer Python home. If pythonhome is found, the pythonpath in the registry will be ignored; otherwise, the pythonpath in the registry will be 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), Python 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 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 file 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.

We can see that,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.

To address 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, if one module A (A. py) has a function getname, the other module cannot import the getname to this module through import a. getname. Only import a can be used. If you want to import only specific classes, functions, and variables, use from a import getname.

Nested Import

Nested import: in two cases, one is: this module imports module A (import a), and another Import action is activated if there is an import statement in module, for example, import B, while Module B can import other modules. It is easy to understand such nesting. Note that the local namespace of each module is independent. Therefore, in the preceding example, after the import of module A is complete, this module can only access module, cannot access 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 a in Module B. 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 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.

    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> is created. Note that _ 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 it is the python. PY, so in SYS. no <moduleb> exists in modules. The value is B first. PY creates a module object (<moduleb>). 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 the dict <Module B>.

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

Execute B. in the process of Py, check the sys. whether the module cache of modules already exists <modulea>. Because the module cache has not been cached <modulea>, similarly, Python internally contains. PY creates a module object (<modulea>), and then, similarly, runs. in py.

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

In this case, the created <moduleb> object is already cached in SYS. in modules, we get <moduleb> directly. However, note that, from the whole process, we know that <moduleb> is still an empty object and there is nothing in it, therefore, the operation that obtains the symbol "D" from this module will throw an exception. If this is only importb, because the "B" symbol already exists in SYS. modules, no exception will be thrown.

The above explanation has been included in the woodpecker by zoom. Quiet. There is a picture in it. You can refer to it.

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. The folder under the package 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 is released to users in the form of packages. The package and module are similar. If you view the package type import sqlalchemy type (sqlalchemy), you can see that
'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_ Init _. pyInstead of 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:

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:

    import sys    import PA.wave  #1    import PA.PB1   #2    import PA.PB1.pb1_m as m1  #3    import PA.PB2.pb2_m #4    PA.wave.getName() #5    m1.getName() #6    PA.PB2.pb2_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. However, you cannot call any module under PA. PB1 (2. The local database has the PA name.

When the execution is completed in, only pa.pb1is loaded into the memory. sys.modulesthere will be paw.wav E, 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.

When the execution is completed 3, The pbsmbs under pa.pb1will be loaded into the memory. sys.leslesthere will be four modules: paw.pa.wav E, Pa. PB1, 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.

After the execution of ipv4, the pa.pb2?pa.pb2.pb2_mwill be loaded into the memory. In sys.lesles, there will be pa1_pa.wav E, Pa. PB1, Pa. pb1.pb1 _ m, Pa. PBS, Pa. pb2.k2_m six. 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, which is not recommended for relative import paths.

[Transfer from] http://blog.163.com/hzr163_2004/blog/static/3308607520092113930771/]

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.