home *** CD-ROM | disk | FTP | other *** search
/ The Datafile PD-CD 5 / DATAFILE_PDCD5.iso / utilities / p / python / pyhtmldoc / e / examples < prev    next >
Text File  |  1996-11-14  |  2KB  |  47 lines

  1. <TITLE>Examples -- Python library reference</TITLE>
  2. Prev: <A HREF="../i/imp" TYPE="Prev">imp</A>  
  3. Up: <A HREF="../i/imp" TYPE="Up">imp</A>  
  4. Top: <A HREF="../t/top" TYPE="Top">Top</A>  
  5. <H2>3.8.1. Examples</H2>
  6. The following function emulates the default import statement:
  7. <P>
  8. <UL COMPACT><CODE>import imp<P>
  9. import sys<P>
  10. <P>
  11. def __import__(name, globals=None, locals=None, fromlist=None):<P>
  12.     # Fast path: see if the module has already been imported.<P>
  13.     if sys.modules.has_key(name):<P>
  14.         return sys.modules[name]<P>
  15. <P>
  16.     # If any of the following calls raises an exception,<P>
  17.     # there's a problem we can't handle -- let the caller handle it.<P>
  18. <P>
  19.     # See if it's a built-in module.<P>
  20.     m = imp.init_builtin(name)<P>
  21.     if m:<P>
  22.         return m<P>
  23. <P>
  24.     # See if it's a frozen module.<P>
  25.     m = imp.init_frozen(name)<P>
  26.     if m:<P>
  27.         return m<P>
  28. <P>
  29.     # Search the default path (i.e. sys.path).<P>
  30.     fp, pathname, (suffix, mode, type) = imp.find_module(name)<P>
  31. <P>
  32.     # See what we got.<P>
  33.     try:<P>
  34.         if type == imp.C_EXTENSION:<P>
  35.             return imp.load_dynamic(name, pathname)<P>
  36.         if type == imp.PY_SOURCE:<P>
  37.             return imp.load_source(name, pathname, fp)<P>
  38.         if type == imp.PY_COMPILED:<P>
  39.             return imp.load_compiled(name, pathname, fp)<P>
  40. <P>
  41.         # Shouldn't get here at all.<P>
  42.         raise ImportError, '%s: unknown module type (%d)' % (name, type)<P>
  43.     finally:<P>
  44.         # Since we may exit via an exception, close fp explicitly.<P>
  45.         fp.close()<P>
  46. </CODE></UL>
  47.