# :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:
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.

Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.