Previous: 3.21 imp Up: 3.21 imp Next: 3.22 code


3.21.1 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 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.


Previous: 3.21 imp Up: 3.21 imp Next: 3.22 code
Release 2.2.3, documentation updated on 30 May 2003.
See About this document... for information on suggesting changes.

AltStyle によって変換されたページ (->オリジナル) /