home *** CD-ROM | disk | FTP | other *** search
- <TITLE>Examples -- Python library reference</TITLE>
- Prev: <A HREF="../i/imp" TYPE="Prev">imp</A>
- Up: <A HREF="../i/imp" TYPE="Up">imp</A>
- Top: <A HREF="../t/top" TYPE="Top">Top</A>
- <H2>3.8.1. Examples</H2>
- The following function emulates the default import statement:
- <P>
- <UL COMPACT><CODE>import imp<P>
- import sys<P>
- <P>
- def __import__(name, globals=None, locals=None, fromlist=None):<P>
- # Fast path: see if the module has already been imported.<P>
- if sys.modules.has_key(name):<P>
- return sys.modules[name]<P>
- <P>
- # If any of the following calls raises an exception,<P>
- # there's a problem we can't handle -- let the caller handle it.<P>
- <P>
- # See if it's a built-in module.<P>
- m = imp.init_builtin(name)<P>
- if m:<P>
- return m<P>
- <P>
- # See if it's a frozen module.<P>
- m = imp.init_frozen(name)<P>
- if m:<P>
- return m<P>
- <P>
- # Search the default path (i.e. sys.path).<P>
- fp, pathname, (suffix, mode, type) = imp.find_module(name)<P>
- <P>
- # See what we got.<P>
- try:<P>
- if type == imp.C_EXTENSION:<P>
- return imp.load_dynamic(name, pathname)<P>
- if type == imp.PY_SOURCE:<P>
- return imp.load_source(name, pathname, fp)<P>
- if type == imp.PY_COMPILED:<P>
- return imp.load_compiled(name, pathname, fp)<P>
- <P>
- # Shouldn't get here at all.<P>
- raise ImportError, '%s: unknown module type (%d)' % (name, type)<P>
- finally:<P>
- # Since we may exit via an exception, close fp explicitly.<P>
- fp.close()<P>
- </CODE></UL>
-