/Lib/imputil.py

http://unladen-swallow.googlecode.com/ · Python · 734 lines · 360 code · 100 blank · 274 comment · 85 complexity · ed0042d97a023effa9b53c2770cad1ad MD5 · raw file

  1. """
  2. Import utilities
  3. Exported classes:
  4. ImportManager Manage the import process
  5. Importer Base class for replacing standard import functions
  6. BuiltinImporter Emulate the import mechanism for builtin and frozen modules
  7. DynLoadSuffixImporter
  8. """
  9. from warnings import warnpy3k
  10. warnpy3k("the imputil module has been removed in Python 3.0", stacklevel=2)
  11. del warnpy3k
  12. # note: avoid importing non-builtin modules
  13. import imp ### not available in JPython?
  14. import sys
  15. import __builtin__
  16. # for the DirectoryImporter
  17. import struct
  18. import marshal
  19. __all__ = ["ImportManager","Importer","BuiltinImporter"]
  20. _StringType = type('')
  21. _ModuleType = type(sys) ### doesn't work in JPython...
  22. class ImportManager:
  23. "Manage the import process."
  24. def install(self, namespace=vars(__builtin__)):
  25. "Install this ImportManager into the specified namespace."
  26. if isinstance(namespace, _ModuleType):
  27. namespace = vars(namespace)
  28. # Note: we have no notion of "chaining"
  29. # Record the previous import hook, then install our own.
  30. self.previous_importer = namespace['__import__']
  31. self.namespace = namespace
  32. namespace['__import__'] = self._import_hook
  33. ### fix this
  34. #namespace['reload'] = self._reload_hook
  35. def uninstall(self):
  36. "Restore the previous import mechanism."
  37. self.namespace['__import__'] = self.previous_importer
  38. def add_suffix(self, suffix, importFunc):
  39. assert callable(importFunc)
  40. self.fs_imp.add_suffix(suffix, importFunc)
  41. ######################################################################
  42. #
  43. # PRIVATE METHODS
  44. #
  45. clsFilesystemImporter = None
  46. def __init__(self, fs_imp=None):
  47. # we're definitely going to be importing something in the future,
  48. # so let's just load the OS-related facilities.
  49. if not _os_stat:
  50. _os_bootstrap()
  51. # This is the Importer that we use for grabbing stuff from the
  52. # filesystem. It defines one more method (import_from_dir) for our use.
  53. if fs_imp is None:
  54. cls = self.clsFilesystemImporter or _FilesystemImporter
  55. fs_imp = cls()
  56. self.fs_imp = fs_imp
  57. # Initialize the set of suffixes that we recognize and import.
  58. # The default will import dynamic-load modules first, followed by
  59. # .py files (or a .py file's cached bytecode)
  60. for desc in imp.get_suffixes():
  61. if desc[2] == imp.C_EXTENSION:
  62. self.add_suffix(desc[0],
  63. DynLoadSuffixImporter(desc).import_file)
  64. self.add_suffix('.py', py_suffix_importer)
  65. def _import_hook(self, fqname, globals=None, locals=None, fromlist=None):
  66. """Python calls this hook to locate and import a module."""
  67. parts = fqname.split('.')
  68. # determine the context of this import
  69. parent = self._determine_import_context(globals)
  70. # if there is a parent, then its importer should manage this import
  71. if parent:
  72. module = parent.__importer__._do_import(parent, parts, fromlist)
  73. if module:
  74. return module
  75. # has the top module already been imported?
  76. try:
  77. top_module = sys.modules[parts[0]]
  78. except KeyError:
  79. # look for the topmost module
  80. top_module = self._import_top_module(parts[0])
  81. if not top_module:
  82. # the topmost module wasn't found at all.
  83. raise ImportError, 'No module named ' + fqname
  84. # fast-path simple imports
  85. if len(parts) == 1:
  86. if not fromlist:
  87. return top_module
  88. if not top_module.__dict__.get('__ispkg__'):
  89. # __ispkg__ isn't defined (the module was not imported by us),
  90. # or it is zero.
  91. #
  92. # In the former case, there is no way that we could import
  93. # sub-modules that occur in the fromlist (but we can't raise an
  94. # error because it may just be names) because we don't know how
  95. # to deal with packages that were imported by other systems.
  96. #
  97. # In the latter case (__ispkg__ == 0), there can't be any sub-
  98. # modules present, so we can just return.
  99. #
  100. # In both cases, since len(parts) == 1, the top_module is also
  101. # the "bottom" which is the defined return when a fromlist
  102. # exists.
  103. return top_module
  104. importer = top_module.__dict__.get('__importer__')
  105. if importer:
  106. return importer._finish_import(top_module, parts[1:], fromlist)
  107. # Grrr, some people "import os.path" or do "from os.path import ..."
  108. if len(parts) == 2 and hasattr(top_module, parts[1]):
  109. if fromlist:
  110. return getattr(top_module, parts[1])
  111. else:
  112. return top_module
  113. # If the importer does not exist, then we have to bail. A missing
  114. # importer means that something else imported the module, and we have
  115. # no knowledge of how to get sub-modules out of the thing.
  116. raise ImportError, 'No module named ' + fqname
  117. def _determine_import_context(self, globals):
  118. """Returns the context in which a module should be imported.
  119. The context could be a loaded (package) module and the imported module
  120. will be looked for within that package. The context could also be None,
  121. meaning there is no context -- the module should be looked for as a
  122. "top-level" module.
  123. """
  124. if not globals or not globals.get('__importer__'):
  125. # globals does not refer to one of our modules or packages. That
  126. # implies there is no relative import context (as far as we are
  127. # concerned), and it should just pick it off the standard path.
  128. return None
  129. # The globals refer to a module or package of ours. It will define
  130. # the context of the new import. Get the module/package fqname.
  131. parent_fqname = globals['__name__']
  132. # if a package is performing the import, then return itself (imports
  133. # refer to pkg contents)
  134. if globals['__ispkg__']:
  135. parent = sys.modules[parent_fqname]
  136. assert globals is parent.__dict__
  137. return parent
  138. i = parent_fqname.rfind('.')
  139. # a module outside of a package has no particular import context
  140. if i == -1:
  141. return None
  142. # if a module in a package is performing the import, then return the
  143. # package (imports refer to siblings)
  144. parent_fqname = parent_fqname[:i]
  145. parent = sys.modules[parent_fqname]
  146. assert parent.__name__ == parent_fqname
  147. return parent
  148. def _import_top_module(self, name):
  149. # scan sys.path looking for a location in the filesystem that contains
  150. # the module, or an Importer object that can import the module.
  151. for item in sys.path:
  152. if isinstance(item, _StringType):
  153. module = self.fs_imp.import_from_dir(item, name)
  154. else:
  155. module = item.import_top(name)
  156. if module:
  157. return module
  158. return None
  159. def _reload_hook(self, module):
  160. "Python calls this hook to reload a module."
  161. # reloading of a module may or may not be possible (depending on the
  162. # importer), but at least we can validate that it's ours to reload
  163. importer = module.__dict__.get('__importer__')
  164. if not importer:
  165. ### oops. now what...
  166. pass
  167. # okay. it is using the imputil system, and we must delegate it, but
  168. # we don't know what to do (yet)
  169. ### we should blast the module dict and do another get_code(). need to
  170. ### flesh this out and add proper docco...
  171. raise SystemError, "reload not yet implemented"
  172. class Importer:
  173. "Base class for replacing standard import functions."
  174. def import_top(self, name):
  175. "Import a top-level module."
  176. return self._import_one(None, name, name)
  177. ######################################################################
  178. #
  179. # PRIVATE METHODS
  180. #
  181. def _finish_import(self, top, parts, fromlist):
  182. # if "a.b.c" was provided, then load the ".b.c" portion down from
  183. # below the top-level module.
  184. bottom = self._load_tail(top, parts)
  185. # if the form is "import a.b.c", then return "a"
  186. if not fromlist:
  187. # no fromlist: return the top of the import tree
  188. return top
  189. # the top module was imported by self.
  190. #
  191. # this means that the bottom module was also imported by self (just
  192. # now, or in the past and we fetched it from sys.modules).
  193. #
  194. # since we imported/handled the bottom module, this means that we can
  195. # also handle its fromlist (and reliably use __ispkg__).
  196. # if the bottom node is a package, then (potentially) import some
  197. # modules.
  198. #
  199. # note: if it is not a package, then "fromlist" refers to names in
  200. # the bottom module rather than modules.
  201. # note: for a mix of names and modules in the fromlist, we will
  202. # import all modules and insert those into the namespace of
  203. # the package module. Python will pick up all fromlist names
  204. # from the bottom (package) module; some will be modules that
  205. # we imported and stored in the namespace, others are expected
  206. # to be present already.
  207. if bottom.__ispkg__:
  208. self._import_fromlist(bottom, fromlist)
  209. # if the form is "from a.b import c, d" then return "b"
  210. return bottom
  211. def _import_one(self, parent, modname, fqname):
  212. "Import a single module."
  213. # has the module already been imported?
  214. try:
  215. return sys.modules[fqname]
  216. except KeyError:
  217. pass
  218. # load the module's code, or fetch the module itself
  219. result = self.get_code(parent, modname, fqname)
  220. if result is None:
  221. return None
  222. module = self._process_result(result, fqname)
  223. # insert the module into its parent
  224. if parent:
  225. setattr(parent, modname, module)
  226. return module
  227. def _process_result(self, (ispkg, code, values), fqname):
  228. # did get_code() return an actual module? (rather than a code object)
  229. is_module = isinstance(code, _ModuleType)
  230. # use the returned module, or create a new one to exec code into
  231. if is_module:
  232. module = code
  233. else:
  234. module = imp.new_module(fqname)
  235. ### record packages a bit differently??
  236. module.__importer__ = self
  237. module.__ispkg__ = ispkg
  238. # insert additional values into the module (before executing the code)
  239. module.__dict__.update(values)
  240. # the module is almost ready... make it visible
  241. sys.modules[fqname] = module
  242. # execute the code within the module's namespace
  243. if not is_module:
  244. try:
  245. exec code in module.__dict__
  246. except:
  247. if fqname in sys.modules:
  248. del sys.modules[fqname]
  249. raise
  250. # fetch from sys.modules instead of returning module directly.
  251. # also make module's __name__ agree with fqname, in case
  252. # the "exec code in module.__dict__" played games on us.
  253. module = sys.modules[fqname]
  254. module.__name__ = fqname
  255. return module
  256. def _load_tail(self, m, parts):
  257. """Import the rest of the modules, down from the top-level module.
  258. Returns the last module in the dotted list of modules.
  259. """
  260. for part in parts:
  261. fqname = "%s.%s" % (m.__name__, part)
  262. m = self._import_one(m, part, fqname)
  263. if not m:
  264. raise ImportError, "No module named " + fqname
  265. return m
  266. def _import_fromlist(self, package, fromlist):
  267. 'Import any sub-modules in the "from" list.'
  268. # if '*' is present in the fromlist, then look for the '__all__'
  269. # variable to find additional items (modules) to import.
  270. if '*' in fromlist:
  271. fromlist = list(fromlist) + \
  272. list(package.__dict__.get('__all__', []))
  273. for sub in fromlist:
  274. # if the name is already present, then don't try to import it (it
  275. # might not be a module!).
  276. if sub != '*' and not hasattr(package, sub):
  277. subname = "%s.%s" % (package.__name__, sub)
  278. submod = self._import_one(package, sub, subname)
  279. if not submod:
  280. raise ImportError, "cannot import name " + subname
  281. def _do_import(self, parent, parts, fromlist):
  282. """Attempt to import the module relative to parent.
  283. This method is used when the import context specifies that <self>
  284. imported the parent module.
  285. """
  286. top_name = parts[0]
  287. top_fqname = parent.__name__ + '.' + top_name
  288. top_module = self._import_one(parent, top_name, top_fqname)
  289. if not top_module:
  290. # this importer and parent could not find the module (relatively)
  291. return None
  292. return self._finish_import(top_module, parts[1:], fromlist)
  293. ######################################################################
  294. #
  295. # METHODS TO OVERRIDE
  296. #
  297. def get_code(self, parent, modname, fqname):
  298. """Find and retrieve the code for the given module.
  299. parent specifies a parent module to define a context for importing. It
  300. may be None, indicating no particular context for the search.
  301. modname specifies a single module (not dotted) within the parent.
  302. fqname specifies the fully-qualified module name. This is a
  303. (potentially) dotted name from the "root" of the module namespace
  304. down to the modname.
  305. If there is no parent, then modname==fqname.
  306. This method should return None, or a 3-tuple.
  307. * If the module was not found, then None should be returned.
  308. * The first item of the 2- or 3-tuple should be the integer 0 or 1,
  309. specifying whether the module that was found is a package or not.
  310. * The second item is the code object for the module (it will be
  311. executed within the new module's namespace). This item can also
  312. be a fully-loaded module object (e.g. loaded from a shared lib).
  313. * The third item is a dictionary of name/value pairs that will be
  314. inserted into new module before the code object is executed. This
  315. is provided in case the module's code expects certain values (such
  316. as where the module was found). When the second item is a module
  317. object, then these names/values will be inserted *after* the module
  318. has been loaded/initialized.
  319. """
  320. raise RuntimeError, "get_code not implemented"
  321. ######################################################################
  322. #
  323. # Some handy stuff for the Importers
  324. #
  325. # byte-compiled file suffix character
  326. _suffix_char = __debug__ and 'c' or 'o'
  327. # byte-compiled file suffix
  328. _suffix = '.py' + _suffix_char
  329. def _compile(pathname, timestamp):
  330. """Compile (and cache) a Python source file.
  331. The file specified by <pathname> is compiled to a code object and
  332. returned.
  333. Presuming the appropriate privileges exist, the bytecodes will be
  334. saved back to the filesystem for future imports. The source file's
  335. modification timestamp must be provided as a Long value.
  336. """
  337. codestring = open(pathname, 'rU').read()
  338. if codestring and codestring[-1] != '\n':
  339. codestring = codestring + '\n'
  340. code = __builtin__.compile(codestring, pathname, 'exec')
  341. # try to cache the compiled code
  342. try:
  343. f = open(pathname + _suffix_char, 'wb')
  344. except IOError:
  345. pass
  346. else:
  347. f.write('\0\0\0\0')
  348. f.write(struct.pack('<I', timestamp))
  349. marshal.dump(code, f)
  350. f.flush()
  351. f.seek(0, 0)
  352. f.write(imp.get_magic())
  353. f.close()
  354. return code
  355. _os_stat = _os_path_join = None
  356. def _os_bootstrap():
  357. "Set up 'os' module replacement functions for use during import bootstrap."
  358. names = sys.builtin_module_names
  359. join = None
  360. if 'posix' in names:
  361. sep = '/'
  362. from posix import stat
  363. elif 'nt' in names:
  364. sep = '\\'
  365. from nt import stat
  366. elif 'dos' in names:
  367. sep = '\\'
  368. from dos import stat
  369. elif 'os2' in names:
  370. sep = '\\'
  371. from os2 import stat
  372. elif 'mac' in names:
  373. from mac import stat
  374. def join(a, b):
  375. if a == '':
  376. return b
  377. if ':' not in a:
  378. a = ':' + a
  379. if a[-1:] != ':':
  380. a = a + ':'
  381. return a + b
  382. else:
  383. raise ImportError, 'no os specific module found'
  384. if join is None:
  385. def join(a, b, sep=sep):
  386. if a == '':
  387. return b
  388. lastchar = a[-1:]
  389. if lastchar == '/' or lastchar == sep:
  390. return a + b
  391. return a + sep + b
  392. global _os_stat
  393. _os_stat = stat
  394. global _os_path_join
  395. _os_path_join = join
  396. def _os_path_isdir(pathname):
  397. "Local replacement for os.path.isdir()."
  398. try:
  399. s = _os_stat(pathname)
  400. except OSError:
  401. return None
  402. return (s.st_mode & 0170000) == 0040000
  403. def _timestamp(pathname):
  404. "Return the file modification time as a Long."
  405. try:
  406. s = _os_stat(pathname)
  407. except OSError:
  408. return None
  409. return long(s.st_mtime)
  410. ######################################################################
  411. #
  412. # Emulate the import mechanism for builtin and frozen modules
  413. #
  414. class BuiltinImporter(Importer):
  415. def get_code(self, parent, modname, fqname):
  416. if parent:
  417. # these modules definitely do not occur within a package context
  418. return None
  419. # look for the module
  420. if imp.is_builtin(modname):
  421. type = imp.C_BUILTIN
  422. elif imp.is_frozen(modname):
  423. type = imp.PY_FROZEN
  424. else:
  425. # not found
  426. return None
  427. # got it. now load and return it.
  428. module = imp.load_module(modname, None, modname, ('', '', type))
  429. return 0, module, { }
  430. ######################################################################
  431. #
  432. # Internal importer used for importing from the filesystem
  433. #
  434. class _FilesystemImporter(Importer):
  435. def __init__(self):
  436. self.suffixes = [ ]
  437. def add_suffix(self, suffix, importFunc):
  438. assert callable(importFunc)
  439. self.suffixes.append((suffix, importFunc))
  440. def import_from_dir(self, dir, fqname):
  441. result = self._import_pathname(_os_path_join(dir, fqname), fqname)
  442. if result:
  443. return self._process_result(result, fqname)
  444. return None
  445. def get_code(self, parent, modname, fqname):
  446. # This importer is never used with an empty parent. Its existence is
  447. # private to the ImportManager. The ImportManager uses the
  448. # import_from_dir() method to import top-level modules/packages.
  449. # This method is only used when we look for a module within a package.
  450. assert parent
  451. for submodule_path in parent.__path__:
  452. code = self._import_pathname(_os_path_join(submodule_path, modname), fqname)
  453. if code is not None:
  454. return code
  455. return self._import_pathname(_os_path_join(parent.__pkgdir__, modname),
  456. fqname)
  457. def _import_pathname(self, pathname, fqname):
  458. if _os_path_isdir(pathname):
  459. result = self._import_pathname(_os_path_join(pathname, '__init__'),
  460. fqname)
  461. if result:
  462. values = result[2]
  463. values['__pkgdir__'] = pathname
  464. values['__path__'] = [ pathname ]
  465. return 1, result[1], values
  466. return None
  467. for suffix, importFunc in self.suffixes:
  468. filename = pathname + suffix
  469. try:
  470. finfo = _os_stat(filename)
  471. except OSError:
  472. pass
  473. else:
  474. return importFunc(filename, finfo, fqname)
  475. return None
  476. ######################################################################
  477. #
  478. # SUFFIX-BASED IMPORTERS
  479. #
  480. def py_suffix_importer(filename, finfo, fqname):
  481. file = filename[:-3] + _suffix
  482. t_py = long(finfo[8])
  483. t_pyc = _timestamp(file)
  484. code = None
  485. if t_pyc is not None and t_pyc >= t_py:
  486. f = open(file, 'rb')
  487. if f.read(4) == imp.get_magic():
  488. t = struct.unpack('<I', f.read(4))[0]
  489. if t == t_py:
  490. code = marshal.load(f)
  491. f.close()
  492. if code is None:
  493. file = filename
  494. code = _compile(file, t_py)
  495. return 0, code, { '__file__' : file }
  496. class DynLoadSuffixImporter:
  497. def __init__(self, desc):
  498. self.desc = desc
  499. def import_file(self, filename, finfo, fqname):
  500. fp = open(filename, self.desc[1])
  501. module = imp.load_module(fqname, fp, filename, self.desc)
  502. module.__file__ = filename
  503. return 0, module, { }
  504. ######################################################################
  505. def _print_importers():
  506. items = sys.modules.items()
  507. items.sort()
  508. for name, module in items:
  509. if module:
  510. print name, module.__dict__.get('__importer__', '-- no importer')
  511. else:
  512. print name, '-- non-existent module'
  513. def _test_revamp():
  514. ImportManager().install()
  515. sys.path.insert(0, BuiltinImporter())
  516. ######################################################################
  517. #
  518. # TODO
  519. #
  520. # from Finn Bock:
  521. # type(sys) is not a module in JPython. what to use instead?
  522. # imp.C_EXTENSION is not in JPython. same for get_suffixes and new_module
  523. #
  524. # given foo.py of:
  525. # import sys
  526. # sys.modules['foo'] = sys
  527. #
  528. # ---- standard import mechanism
  529. # >>> import foo
  530. # >>> foo
  531. # <module 'sys' (built-in)>
  532. #
  533. # ---- revamped import mechanism
  534. # >>> import imputil
  535. # >>> imputil._test_revamp()
  536. # >>> import foo
  537. # >>> foo
  538. # <module 'foo' from 'foo.py'>
  539. #
  540. #
  541. # from MAL:
  542. # should BuiltinImporter exist in sys.path or hard-wired in ImportManager?
  543. # need __path__ processing
  544. # performance
  545. # move chaining to a subclass [gjs: it's been nuked]
  546. # deinstall should be possible
  547. # query mechanism needed: is a specific Importer installed?
  548. # py/pyc/pyo piping hooks to filter/process these files
  549. # wish list:
  550. # distutils importer hooked to list of standard Internet repositories
  551. # module->file location mapper to speed FS-based imports
  552. # relative imports
  553. # keep chaining so that it can play nice with other import hooks
  554. #
  555. # from Gordon:
  556. # push MAL's mapper into sys.path[0] as a cache (hard-coded for apps)
  557. #
  558. # from Guido:
  559. # need to change sys.* references for rexec environs
  560. # need hook for MAL's walk-me-up import strategy, or Tim's absolute strategy
  561. # watch out for sys.modules[...] is None
  562. # flag to force absolute imports? (speeds _determine_import_context and
  563. # checking for a relative module)
  564. # insert names of archives into sys.path (see quote below)
  565. # note: reload does NOT blast module dict
  566. # shift import mechanisms and policies around; provide for hooks, overrides
  567. # (see quote below)
  568. # add get_source stuff
  569. # get_topcode and get_subcode
  570. # CRLF handling in _compile
  571. # race condition in _compile
  572. # refactoring of os.py to deal with _os_bootstrap problem
  573. # any special handling to do for importing a module with a SyntaxError?
  574. # (e.g. clean up the traceback)
  575. # implement "domain" for path-type functionality using pkg namespace
  576. # (rather than FS-names like __path__)
  577. # don't use the word "private"... maybe "internal"
  578. #
  579. #
  580. # Guido's comments on sys.path caching:
  581. #
  582. # We could cache this in a dictionary: the ImportManager can have a
  583. # cache dict mapping pathnames to importer objects, and a separate
  584. # method for coming up with an importer given a pathname that's not yet
  585. # in the cache. The method should do a stat and/or look at the
  586. # extension to decide which importer class to use; you can register new
  587. # importer classes by registering a suffix or a Boolean function, plus a
  588. # class. If you register a new importer class, the cache is zapped.
  589. # The cache is independent from sys.path (but maintained per
  590. # ImportManager instance) so that rearrangements of sys.path do the
  591. # right thing. If a path is dropped from sys.path the corresponding
  592. # cache entry is simply no longer used.
  593. #
  594. # My/Guido's comments on factoring ImportManager and Importer:
  595. #
  596. # > However, we still have a tension occurring here:
  597. # >
  598. # > 1) implementing policy in ImportManager assists in single-point policy
  599. # > changes for app/rexec situations
  600. # > 2) implementing policy in Importer assists in package-private policy
  601. # > changes for normal, operating conditions
  602. # >
  603. # > I'll see if I can sort out a way to do this. Maybe the Importer class will
  604. # > implement the methods (which can be overridden to change policy) by
  605. # > delegating to ImportManager.
  606. #
  607. # Maybe also think about what kind of policies an Importer would be
  608. # likely to want to change. I have a feeling that a lot of the code
  609. # there is actually not so much policy but a *necessity* to get things
  610. # working given the calling conventions for the __import__ hook: whether
  611. # to return the head or tail of a dotted name, or when to do the "finish
  612. # fromlist" stuff.
  613. #