频道栏目
首页 > 程序开发 > Web开发 > python教程 > Python v3.4.3 语言参考 > 正文
5. 导入系统 Python v3.4.3 语言参考
2016-01-11 18:01:55           
收藏   我要投稿

Python code in one module gains access to the code in another module by the process of importing it. The import statement is the most common way of invoking the import machinery, but it is not the only way. Functions such asimportlib.import_module() and built-in __import__() can also be used to invoke the import machinery.

The import statement combines two operations; it searches for the named module, then it binds the results of that search to a name in the local scope. The search operation of the import statement is defined as a call to the__import__() function, with the appropriate arguments. The return value of __import__() is used to perform the name binding operation of the import statement. See the import statement for the exact details of that name binding operation.

A direct call to __import__() performs only the module search and, if found, the module creation operation. While certain side-effects may occur, such as the importing of parent packages, and the updating of various caches (including sys.modules), only the import statement performs a name binding operation.

When calling __import__() as part of an import statement, the import system first checks the module global namespace for a function by that name. If it is not found, then the standard builtin __import__() is called. Other mechanisms for invoking the import system (such as importlib.import_module()) do not perform this check and will always use the standard import system.

When a module is first imported, Python searches for the module and if found, it creates a module object [1], initializing it. If the named module cannot be found, an ImportError is raised. Python implements various strategies to search for the named module when the import machinery is invoked. These strategies can be modified and extended by using various hooks described in the sections below.

Changed in version 3.3: The import system has been updated to fully implement the second phase of PEP 302There is no longer any implicit import machinery - the full import system is exposed through sys.meta_pathIn addition, native namespace package support has been implemented (see PEP 420).

5.1. importlib

 importlib 模块提供了丰富的API和导入系统进行交互。例如importlib.import_module() 提供了一个比内建模块__import__() 更加推荐,更容易的API调用导入系统。可以查看importlib 模块的文档获取更多细节。

5.2. 包

Python 只有一种模块对象,所有的模块都是这种类型,不管这个模块是否是用Python,C,或者其他语言实现。为了组织模块和提供命名层次, Python 引入 packages的概念。

你可以认为