What is the point of Python's importlib?

2019-07-05 00:38发布

问题:

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?

回答1:

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)]'
>>>

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

In Python versions 3.1 and greater however, the purpose of importlib has been expanded. According to the 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 PEP 302.

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.

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.

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.

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



回答2:

It allows you to import modules which you do not know the name at coding time.

For instance when my application starts, I walk through a directory structure and load the modules as I discover them.