GNU Info

Info Node: (python2.1-lib.info)Examples

(python2.1-lib.info)Examples


Prev: imp Up: imp
Enter node , (file) or (file)node

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 module `knee' .


automatically generated by info2www version 1.2.2.9