cpython_sandbox / Doc / library / imp.rst

:mod:`imp` --- Access the :ref:`import <importsystem>` 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 functions are conveniences for handling PEP 3147 byte-compiled file paths.

The following functions help interact with the import system's internal locking mechanism. Locking semantics of imports are an implementation detail which may vary from release to release. However, Python ensures that circular imports work without any deadlocks.

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

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.

Instances have only one method:


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.
        return sys.modules[name]
    except KeyError:

    # 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)

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