Examples -- Python library reference



Prev: imp Up: imp Top: Top

3.8.1. Examples

The following function emulates the default import statement:

import imp

import sys

def __import__(name, globals=None, locals=None, fromlist=None):

# Fast path: see if the module has already been imported.

if sys.modules.has_key(name):

return sys.modules[name]

# If any of the following calls raises an exception,

# there's a problem we can't handle -- let the caller handle it.

# See if it's a built-in module.

m = imp.init_builtin(name)

if m:

return m

# See if it's a frozen module.

m = imp.init_frozen(name)

if m:

return m

# Search the default path (i.e. sys.path).

fp, pathname, (suffix, mode, type) = imp.find_module(name)

# See what we got.

try:

if type == imp.C_EXTENSION:

return imp.load_dynamic(name, pathname)

if type == imp.PY_SOURCE:

return imp.load_source(name, pathname, fp)

if type == imp.PY_COMPILED:

return imp.load_compiled(name, pathname, fp)

# Shouldn't get here at all.

raise ImportError, '%s: unknown module type (%d)' % (name, type)

finally:

# Since we may exit via an exception, close fp explicitly.

fp.close()



Prev: imp Up: imp Top: Top