3.13.1 Examples

The following function emulates what was the standard import statement up to Python 1.4 (i.e., no hierarchical module names). (This implementation wouldn't work in that version, since find_module() has been extended and 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 reload()  function can be found in the standard module knee  (which is intended as an example only -- don't rely on any part of it being a standard interface).


guido@python.org