The mechanism of import in Python __python

Source: Internet
Author: User
Introduction : The point in Python from. Importxxx represents the current package.

My understanding is from. Import xxx defaults to importing XXX in the current program's folder in the init. PY program, which cannot be written if the current program is in a folder without the init. py file, and should be written from. A import Xxx,a is the name of a function (or other) that you want to import under the current folder, and if you want to import a function that is not in the current folder, you might use from. Import XXX (that is, init. Py in the previous folder), or from.. A import XXX (that is, file a in the previous folder) import a packet:
When you import a folder (Python is called packet), you execute init. py. Each package preferably has a init_.py module. When you import a file under this folder, First run init. PY, and then run the code for this module.
If you import a module under a child file under this folder, execute all init. Py in the parent folder sequentially, then execute the file's init. PY, and then execute the module.
It is best to have the all list in each init. py. two kinds of introduction mechanisms of Python

Python offers two kinds of introduction mechanisms:
-Relative Import
-Absolute Import
* Relative import, also called relative introduction, in Python2.5 and before is the default method of introduction. It is used in the following ways:

From. String import a from
. String import a from
... string import a
Absolute import is absolutely imported, after Python2.6 and Python3, full reference is the default introduction mechanism for Python。 It is used in the following ways:
From pkg import foo
pkg.modulea import foo

Note that you need to write from the top-most directory of the package directory and not start from the middle.

since the relative import is no longer in use, the following content is only for absolute miport. the definition of module and package

Module: The essence of a. py end file (logically organizing Python code) The essence of the module is to implement a feature file name is the module.
Package: A folder with init. py; for storing module file Import module

Basic format:

Import module name
form module name import * from
Module name import module name as new name

The nature of the import module:
-Import Module NAME = = = Assign all of the data in the module to the module name, and the module name is required when called. Method name ()
-From Module name Import method name = = To run the method separately in the current file, which requires only the method name () to be invoked. detailed mechanisms for importing modules

1. Standard Import:

All modules loaded into memory in Python are placed in sys.modules. When you import a module, you first look in this list to see if the module has already been loaded, and if it does, just add the name of the module to the local namespace of the module that is calling import. If not loaded, the module file is searched from the Sys.path directory according to the module name, the module can be py, PYC, PYD, the module is loaded into memory after it is found, added to the Sys.modules, and the name is imported into the current local namespace.

A module does not repeat loading. Many different modules can be imported into the same module with the local name space, in fact, behind the Pymoduleobject object only one.

Here's an easy to ignore problem: Importonly imports modules and cannot import objects (classes, functions, variables, and so on) in the module. For example, there is a function getName in module A (a.py), and another module cannot import the GetName function into this module through the import A.getname, only from import getName.

2. Nested import:

1) Sequential nesting

For example: This module imports a module (import a), A and import b,b modules can import other modules ...
This nesting is easy to understand and one thing to note is that each module's local namespace is independent . For the above example, after import a of this module, this module can only access module A and cannot access module B and other modules. Although module B is already loaded into memory, if the access is further explicit in this module, import B.

2) Loop nesting
For example:

Why can't I load D when I execute a.
If you change the a.py to: Import B is OK.
What the hell is going on here?

This is related to the mechanism of the internal import of Python, which is divided into several steps within the From B import D,python:
(1) Find the symbol "B" in Sys.modules
(2) If symbol B exists, the module object corresponding to symbol B is obtained.
The object corresponding to the symbol "D" is then obtained from the dict , and an exception is thrown if "D" does not exist.
(3) If symbol B does not exist, create a new module object, noting that at this point, the dict of the module object is empty.
Executes the code in b.py and fills the dict. (In this case, the b.py will also require import a, so the fill for dict cannot be completed)
Gets the object corresponding to "D" from the dict and throws an exception if "D" does not exist. (b.py from import C is not done, ' class D:pass ' cannot be executed, D cannot be found in dict )

So this example is executed in the following order:

1, the implementation of the a.py from B import D . Because it is an executing Python a.py that does not exist in Sys.modules, first create a Module object for b.py (), and note that the module object created here is empty and nothing inside, creating this inside python After the module object, the execution b.py is parsed to populate the dict.
2, the implementation of the b.py from A import C . In the process of performing b.py, you will encounter this sentence, first check the Sys.modules this module cache is already in existence, because the cache is not yet cached, so similarly, Python will create a module object for a.py (), and then, similarly, Execute the statement in a.py
3. execute a.py from B import D again. At this point, because the object created in step 1th is already slow to exist in the sys.modules, it is immediately available, but note that
-From the whole process, we know that this is still an empty object with nothing in it, so getting the symbol "D" from this module throws an exception.
-If this is only import B, because the symbol "B" already exists in the sys.modules, it will not throw an exception. Import Package

the nature of the import package: Importing a package is the execution of the _init_.py file under the package

As long as there is an init. py file at the bottom of a folder, this folder can be considered a package. The process of package import is basically the same as that of the module, except that the init. PY in the package directory is executed when the package is imported and not the statements in the module. In addition, if you are simply importing packages and there are no explicit other initialization actions in the package init. PY, the modules below this package will not be imported automatically.
For example:
The following package structure is available:
Pa

The following procedures are available:

Import SYS import Pa.wave    #         
import PA. PB1                to
import PA. Pb1.pb1_m as M1    #3
import PA. Pb2.pb2_m          #4
PA.wave.getName ()           #5
m1.getname ()                #6
PA. PB.pb2_m.getName ()       #7

1 after the execution of the #1, Sys.modules will also have the PA, pa.wave two modules, at this time can call any Pa.wave class or function. But you cannot call PA. Any module under PB1 (2). There is a PA name in the current local.

2 when executing the #2, just the PA. PB1 loaded into memory, Sys.modules will have PA, Pa.wave, Pa. PB1 three modules, but PA. Any modules under PB1 are not automatically loaded into memory, at which point if the PA is executed directly. PB1.pb1_m.getName () can be faulted because the PA. There is no pb1_m in the PB1. (If it's just a simple import package, and the package's init. PY has no explicit other initialization, the module below this package will not be imported automatically.) The current local or only PA name, and no Pa. PB1 name.

3 When the #3 is executed, the PA. PB1 under the pb1_m load memory, Sys.modules will have PA, Pa.wave, Pa. PB1, PA. Pb1.pb1_m four modules, the PA can be executed at this time. PB1.pb1_m.getName (). Because of the use of as, the current local in addition to the PA name, added M1 as Pa. Alias for Pb1.pb1_m.

4 when the #4 is executed, the PA. PB2, PA. Pb2.pb2_m loaded into memory, Sys.modules will have PA, Pa.wave, Pa. PB1, PA. Pb1.pb1_m, PA. PB2, PA. Pb2.pb2_m six modules. Current local or only PA, M1 (author: this sentence is not understood.) )。
The following #5, #6, #7 can be run correctly. Python search Path

Actions on the search path

Import Sys,os

Os.path.abspath (__file__) #获取当前文件的全名

os.path.dirname () #获取当前对象的父级目录

Sys.path.insert () # Adds the current object's path to the first

sys.path.append () # Adds the current environment variable to the end of the environment variable

Reference articles
A detailed explanation of the import mechanism of Python
Http://www.jb51.net/article/51815.htm
Http://www.jb51.net/article/118358.htm
On the introduction of Python import modules under different paths
Http://www.jb51.net/article/118367.htm

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.