What's the point of Python importlib?
Is this a "convenience wrapper": https://docs.python.org/2/library/importlib.html , just by providing a different way of writing:
import path.to.my.module
Is there something that you cannot do with a normal import operation?
source to share
In Python 2.7, importlib
not very useful. In fact, its only function is a function import_module
that allows 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 can do the same with __import__
, but usually use import_module
.
However, in Python 3.1 and above, the target has importlib
been extended. According to the documentation :
The purpose of the package
importlib
is twofold. One is to provide implementations of the import statement (and thus__import__()
) in the Python source code. This provides an implementationimport
that is portable to any Python interpreter. It also provides a referential implementation that is in comparison to one implemented in a programming language other than Python.The two importing components appear in this package, making it easier for users to create their own custom objects (known as the importer) to participate in the import process. Details on custom importers can be found in PEP 302 .
Generalized importlib
now allows you to access the internals of Python imports, create custom search engines, loaders and importers, customize import hooks, and more.
In fact, starting from version 3.3, it importlib
implements the import-operator itself. You can read about this on the What's New in Python 3.3 page under Using importlib
as an Import Implementation .
It importlib
will also replace old import related modules in future Python versions. For example, the old imp
module was deprecated in version 3.4 in favor of importlib
.
With all this in mind, I'm sure it's importlib
pretty important in modern Python.;)
source to share