Python的importlib有什么意义

Python的importlib有什么意义

本文介绍了Python的importlib有什么意义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是便利包装:只提供另一种写作方式:

Is this "convenience wrapper": https://docs.python.org/2/library/importlib.html just providing another way of writing:

import path.to.my.module

对于正常的导入声明,你有什么不能做的吗?

Is there something is does that you can't do with a normal import statement?

推荐答案

在Python 2.7中, importlib 不是 super 有用。事实上,它唯一的功能是 import_module 函数,它允许您从字符串名称导入模块:

In Python 2.7, importlib isn't super useful. In fact, its only feature is the import_module function, which enables you to import a module from a string name:

>>> import importlib
>>> importlib.import_module('sys')
<module 'sys' (built-in)>
>>> importlib.import_module('sys').version
'2.7.8 (default, Jul  2 2014, 19:50:44) [MSC v.1500 32 bit (Intel)]'
>>>

请注意,您可以对内置,但使用 import_module 通常是首选。

Note that you could do the same with the __import__ built-in, but using import_module is generally preferred.

然而,在Python 3.1及更高版本中, importlib 已经扩大。根据:

In Python versions 3.1 and greater however, the purpose of importlib has been expanded. According to the documentation:

2 ,实现导入的组件在此包中公开,
使用户可以更轻松地创建自己的自定义对象(通常称为
作为导入程序)来参与导入过程。
有关自定义导入程序的详细信息,请参见。

Two, the components to implement import are exposed in this package, making it easier for users to create their own custom objects (known generically as an importer) to participate in the import process. Details on custom importers can be found in PEP 302.

汇总, importlib 现在允许您访问Python的import-statement的内部,构建自定义查找程序,加载程序和导入程序,设置导入挂钩等等。

Summarized, importlib now allows you to access the internals of Python's import-statement, build custom finders, loaders, and importers, setup import hooks, and much more.

事实上,从版本3.3开始, importlib 持有import-statement本身的实现。您可以在。

In fact, as of version 3.3, importlib holds the implementation of the import-statement itself. You can read about this on the What's New in Python 3.3 page under Using importlib as the Implementation of Import.

此外, importlib 将在未来的Python版本中替换与导入相关的旧模块。例如,旧的模块在版本3.4中被弃用,而不是 importlib

Also, importlib will be replacing older modules related to importing in future versions of Python. For example, the old imp module was deprecated in version 3.4 in favor of importlib.

考虑到所有这些,我猜可以肯定地说, importlib 在现代Python中非常重要。 ;)

With all of this in mind, I guess it's safe to say that importlib is pretty important in modern Python. ;)

这篇关于Python的importlib有什么意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 04:03