Difference between 'imp' and 'importlib'

Eric Snow ericsnowcurrently at gmail.com
Sat Apr 21 00:02:59 EDT 2012


On Fri, Apr 20, 2012 at 1:30 AM, Frank Millman <frank at chagford.com> wrote:
> Hi all
>
> I need the ability to execute a function by parsing a string containing the
> full path to the function. The string is multi-dotted. The last element is
> the function name, the second-last is the name of the module containing the
> function, and the balance is the path to the module.
>
> I have been using 'import imp', and then 'imp.find_module' and
> 'imp.load_module'. It works, but I noticed that it would reload the module
> if it was already loaded.
>
> As an alternative, I tried 'import importlib', and then
> 'importlib.import_module'. This also works, and does not reload the module.
>
> So my question is, is there any practical difference between the two
> approaches? What about 'There should be one-- and preferably only
> one --obvious way to do it'?

importlib.import_module() is the preferred approach.  It's API has no
direct analog in the imp module, and is easier to use.  As of 3.3,
importlib is used as the default import implementation for the
interpreter.  The imp module is quickly becoming irrelevant, so using
the standard machinery (importlib) is advisable.

-eric



More information about the Python-list mailing list