Python's imp.load_module

imp.load_module(name, file, pathname, description)

parameters

  • name: module name using dot-notation for sub-directories (e.g. directory.module)
  • file: Opened file (module)
  • pathname: The path to the file.
  • description: The tuple returned by imp.find_module

Examples

Same Directory

The equivalent of import module:


f, p, d = find_module('module')
module = load_module('module', f, p, d)
Sub-Directory

The equivalent of import package.module:


path_to_importer = os.path.dirname(__file__)
f, p, d = find_module('package', [path_to_importer])
f2, p2, d2 = find_module('module', [p])
o = load_module('package.module', f2, p2, d2)
Close the File

The importer won't close the file, even if there is an exception. To make sure it gets closed:


try:
return load_module('package.module', f2, p2, d2)
finally:
if f2:
f2.close()