在Python 2.7中,importlib并不是超级有用.实际上,它的唯一功能是import_module函数,它使您能够从字符串名称导入模块:
>>> import importlib
>>> importlib.import_module('sys')
>>> importlib.import_module('sys').version
'2.7.8 (default, Jul 2 2014, 19:50:44) [MSC v.1500 32 bit (Intel)]'
>>>
请注意,您可以使用内置的__import__进行相同的操作,但是通常首选使用import_module.
但是,在Python 3.1及更高版本中,importlib的用途已得到扩展.根据documentation:
The purpose of the importlib package is two-fold. One is to provide an
implementation of the import statement (and thus, by extension, the
__import__() function) in Python source code. This provides an implementation of import which is portable to any Python interpreter.
This also provides a reference implementation which is easier to
comprehend than one implemented in a programming language other than
Python.
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 07002.
综上所述,importlib现在允许您访问Python的import语句的内部,构建自定义查找器,加载器和导入器,设置导入钩子等等.
实际上,从版本3.3开始,importlib保留了导入语句本身的实现.您可以在Using importlib as the Implementation of Import下的“ Python 3.3新增功能”页面中了解此内容.
另外,importlib将替换与将来的Python版本中的导入相关的旧模块.例如,版本3.4中不推荐使用旧的imp模块,而推荐使用importlib.
考虑到所有这些,我想可以肯定地说importlib在现代Python中非常重要. ?