Source

sandbox/antoine / Doc / library / imp.rst

Full commit

:mod:`imp` --- Access the :keyword:`import` internals

This module provides an interface to the mechanisms used to implement the :keyword:`import` statement. It defines the following constants and functions:

The following constants with integer values, defined in this module, are used to indicate the search result of :func:`find_module`.

The following constant and functions are obsolete; their functionality is available through :func:`find_module` or :func:`load_module`. They are kept around for backward compatibility:

The :class:`NullImporter` type is a PEP 302 import hook that handles non-directory path strings by failing to find any modules. Calling this type with an existing directory or empty string raises :exc:`ImportError`. Otherwise, a :class:`NullImporter` instance is returned.

Python adds instances of this type to sys.path_importer_cache for any path entries that are not directories and are not handled by any other path hooks on sys.path_hooks. Instances have only one method:

Examples

The following function emulates what was the standard import statement up to Python 1.4 (no hierarchical module names). (This implementation wouldn't work in that version, since :func:`find_module` has been extended and :func:`load_module` has been added in 1.4.)

import imp
import sys

def __import__(name, globals=None, locals=None, fromlist=None):
    # Fast path: see if the module has already been imported.
    try:
        return sys.modules[name]
    except KeyError:
        pass

    # If any of the following calls raises an exception,
    # there's a problem we can't handle -- let the caller handle it.

    fp, pathname, description = imp.find_module(name)

    try:
        return imp.load_module(name, fp, pathname, description)
    finally:
        # Since we may exit via an exception, close fp explicitly.
        if fp:
            fp.close()

A more complete example that implements hierarchical module names and includes a :func:`reload` function can be found in the module :mod:`knee`. The :mod:`knee` module can be found in :file:`Demo/imputil/` in the Python source distribution.