5 ImportManager Manage the import process
7 Importer Base class for replacing standard import functions
8 BuiltinImporter Emulate the import mechanism for builtin and frozen modules
22 __all__ = [
"ImportManager",
"Importer",
"BuiltinImporter"]
24 _StringType = type(
'')
25 _ModuleType = type(sys)
28 "Manage the import process."
30 def install(self, namespace=vars(__builtin__)):
31 "Install this ImportManager into the specified namespace."
33 if isinstance(namespace, _ModuleType):
34 namespace = vars(namespace)
47 "Restore the previous import mechanism."
51 assert callable(importFunc)
52 self.fs_imp.add_suffix(suffix, importFunc)
59 clsFilesystemImporter =
None
77 for desc
in imp.get_suffixes():
78 if desc[2] == imp.C_EXTENSION:
83 def _import_hook(self, fqname, globals=None, locals=None, fromlist=None):
84 """Python calls this hook to locate and import a module."""
86 parts = fqname.split(
'.')
93 module = parent.__importer__._do_import(parent, parts, fromlist)
99 top_module = sys.modules[parts[0]]
106 raise ImportError,
'No module named ' + fqname
113 if not top_module.__dict__.get(
'__ispkg__'):
130 importer = top_module.__dict__.get(
'__importer__')
132 return importer._finish_import(top_module, parts[1:], fromlist)
135 if len(parts) == 2
and hasattr(top_module, parts[1]):
141 raise ImportError,
'No module named ' + fqname
143 def _determine_import_context(self, globals):
144 """Returns the context in which a module should be imported.
146 The context could be a loaded (package) module and the imported module
147 will be looked for within that package. The context could also be None,
148 meaning there is no context -- the module should be looked for as a
152 if not globals
or not globals.get(
'__importer__'):
160 parent_fqname = globals[
'__name__']
164 if globals[
'__ispkg__']:
165 parent = sys.modules[parent_fqname]
166 assert globals
is parent.__dict__
169 i = parent_fqname.rfind(
'.')
177 parent_fqname = parent_fqname[:i]
178 parent = sys.modules[parent_fqname]
179 assert parent.__name__ == parent_fqname
182 def _import_top_module(self, name):
185 for item
in sys.path:
186 if isinstance(item, _StringType):
187 module = self.fs_imp.import_from_dir(item, name)
189 module = item.import_top(name)
194 def _reload_hook(self, module):
195 "Python calls this hook to reload a module."
199 importer = module.__dict__.get(
'__importer__')
208 raise SystemError,
"reload not yet implemented"
212 "Base class for replacing standard import functions."
215 "Import a top-level module."
222 def _finish_import(self, top, parts, fromlist):
257 def _import_one(self, parent, modname, fqname):
258 "Import a single module."
262 return sys.modules[fqname]
267 result = self.
get_code(parent, modname, fqname)
275 setattr(parent, modname, module)
278 def _process_result(self, (ispkg, code, values), fqname):
280 is_module = isinstance(code, _ModuleType)
286 module = imp.new_module(fqname)
289 module.__importer__ = self
290 module.__ispkg__ = ispkg
293 module.__dict__.update(values)
296 sys.modules[fqname] = module
300 exec code
in module.__dict__
305 module = sys.modules[fqname]
306 module.__name__ = fqname
309 def _load_tail(self, m, parts):
310 """Import the rest of the modules, down from the top-level module.
312 Returns the last module in the dotted list of modules.
315 fqname =
"%s.%s" % (m.__name__, part)
318 raise ImportError,
"No module named " + fqname
321 def _import_fromlist(self, package, fromlist):
322 'Import any sub-modules in the "from" list.'
327 fromlist = list(fromlist) + \
328 list(package.__dict__.get(
'__all__', []))
333 if sub !=
'*' and not hasattr(package, sub):
334 subname =
"%s.%s" % (package.__name__, sub)
337 raise ImportError,
"cannot import name " + subname
339 def _do_import(self, parent, parts, fromlist):
340 """Attempt to import the module relative to parent.
342 This method is used when the import context specifies that <self>
343 imported the parent module.
346 top_fqname = parent.__name__ +
'.' + top_name
347 top_module = self.
_import_one(parent, top_name, top_fqname)
359 """Find and retrieve the code for the given module.
361 parent specifies a parent module to define a context for importing. It
362 may be None, indicating no particular context for the search.
364 modname specifies a single module (not dotted) within the parent.
366 fqname specifies the fully-qualified module name. This is a
367 (potentially) dotted name from the "root" of the module namespace
369 If there is no parent, then modname==fqname.
371 This method should return None, or a 3-tuple.
373 * If the module was not found, then None should be returned.
375 * The first item of the 2- or 3-tuple should be the integer 0 or 1,
376 specifying whether the module that was found is a package or not.
378 * The second item is the code object for the module (it will be
379 executed within the new module's namespace). This item can also
380 be a fully-loaded module object (e.g. loaded from a shared lib).
382 * The third item is a dictionary of name/value pairs that will be
383 inserted into new module before the code object is executed. This
384 is provided in case the module's code expects certain values (such
385 as where the module was found). When the second item is a module
386 object, then these names/values will be inserted *after* the module
387 has been loaded/initialized.
389 raise RuntimeError,
"get_code not implemented"
398 _suffix_char = __debug__
and 'c' or 'o'
401 _suffix =
'.py' + _suffix_char
403 def _compile(pathname, timestamp):
404 """Compile (and cache) a Python source file.
406 The file specified by <pathname> is compiled to a code object and
409 Presuming the appropriate privileges exist, the bytecodes will be
410 saved back to the filesystem for future imports. The source file's
411 modification timestamp must be provided as a Long value.
413 codestring =
open(pathname,
'r').read()
414 if codestring
and codestring[-1] !=
'\n':
415 codestring = codestring +
'\n'
416 code = __builtin__.compile(codestring, pathname,
'exec')
420 f =
open(pathname + _suffix_char,
'wb')
425 f.write(struct.pack(
'<I', timestamp))
426 marshal.dump(code, f)
429 f.write(imp.get_magic())
434 _os_stat = _os_path_join =
None
436 "Set up 'os' module replacement functions for use during import bootstrap."
438 names = sys.builtin_module_names
443 from posix
import stat
465 raise ImportError,
'no os specific module found'
468 def join(a, b, sep=sep):
472 if lastchar ==
'/' or lastchar == sep:
482 def _os_path_isdir(pathname):
483 "Local replacement for os.path.isdir()."
488 return (s[0] & 0170000) == 0040000
490 def _timestamp(pathname):
491 "Return the file modification time as a Long."
510 if imp.is_builtin(modname):
512 elif imp.is_frozen(modname):
519 module = imp.load_module(modname,
None, modname, (
'',
'', type))
520 return 0, module, { }
532 assert callable(importFunc)
533 self.suffixes.append((suffix, importFunc))
551 def _import_pathname(self, pathname, fqname):
552 if _os_path_isdir(pathname):
557 values[
'__pkgdir__'] = pathname
558 values[
'__path__'] = [ pathname ]
559 return 1, result[1], values
562 for suffix, importFunc
in self.
suffixes:
563 filename = pathname + suffix
569 return importFunc(filename, finfo, fqname)
578 file = filename[:-3] + _suffix
579 t_py = long(finfo[8])
580 t_pyc = _timestamp(file)
583 if t_pyc
is not None and t_pyc >= t_py:
585 if f.read(4) == imp.get_magic():
586 t = struct.unpack(
'<I', f.read(4))[0]
588 code = marshal.load(f)
592 code = _compile(file, t_py)
594 return 0, code, {
'__file__' : file }
602 module = imp.load_module(fqname, fp, filename, self.
desc)
603 module.__file__ = filename
604 return 0, module, { }
609 def _print_importers():
610 items = sys.modules.items()
612 for name, module
in items:
614 print name, module.__dict__.get(
'__importer__',
'-- no importer')
616 print name,
'-- non-existent module'