ihooks.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. """Import hook support.
  2. Consistent use of this module will make it possible to change the
  3. different mechanisms involved in loading modules independently.
  4. While the built-in module imp exports interfaces to the built-in
  5. module searching and loading algorithm, and it is possible to replace
  6. the built-in function __import__ in order to change the semantics of
  7. the import statement, until now it has been difficult to combine the
  8. effect of different __import__ hacks, like loading modules from URLs
  9. by rimport.py, or restricted execution by rexec.py.
  10. This module defines three new concepts:
  11. 1) A "file system hooks" class provides an interface to a filesystem.
  12. One hooks class is defined (Hooks), which uses the interface provided
  13. by standard modules os and os.path. It should be used as the base
  14. class for other hooks classes.
  15. 2) A "module loader" class provides an interface to search for a
  16. module in a search path and to load it. It defines a method which
  17. searches for a module in a single directory; by overriding this method
  18. one can redefine the details of the search. If the directory is None,
  19. built-in and frozen modules are searched instead.
  20. Two module loader class are defined, both implementing the search
  21. strategy used by the built-in __import__ function: ModuleLoader uses
  22. the imp module's find_module interface, while HookableModuleLoader
  23. uses a file system hooks class to interact with the file system. Both
  24. use the imp module's load_* interfaces to actually load the module.
  25. 3) A "module importer" class provides an interface to import a
  26. module, as well as interfaces to reload and unload a module. It also
  27. provides interfaces to install and uninstall itself instead of the
  28. default __import__ and reload (and unload) functions.
  29. One module importer class is defined (ModuleImporter), which uses a
  30. module loader instance passed in (by default HookableModuleLoader is
  31. instantiated).
  32. The classes defined here should be used as base classes for extended
  33. functionality along those lines.
  34. If a module importer class supports dotted names, its import_module()
  35. must return a different value depending on whether it is called on
  36. behalf of a "from ... import ..." statement or not. (This is caused
  37. by the way the __import__ hook is used by the Python interpreter.) It
  38. would also do wise to install a different version of reload().
  39. """
  40. import __builtin__
  41. import imp
  42. import os
  43. import sys
  44. __all__ = ["BasicModuleLoader","Hooks","ModuleLoader","FancyModuleLoader",
  45. "BasicModuleImporter","ModuleImporter","install","uninstall"]
  46. VERBOSE = 0
  47. from imp import C_EXTENSION, PY_SOURCE, PY_COMPILED
  48. from imp import C_BUILTIN, PY_FROZEN, PKG_DIRECTORY
  49. BUILTIN_MODULE = C_BUILTIN
  50. FROZEN_MODULE = PY_FROZEN
  51. class _Verbose:
  52. def __init__(self, verbose = VERBOSE):
  53. self.verbose = verbose
  54. def get_verbose(self):
  55. return self.verbose
  56. def set_verbose(self, verbose):
  57. self.verbose = verbose
  58. # XXX The following is an experimental interface
  59. def note(self, *args):
  60. if self.verbose:
  61. self.message(*args)
  62. def message(self, format, *args):
  63. if args:
  64. print format%args
  65. else:
  66. print format
  67. class BasicModuleLoader(_Verbose):
  68. """Basic module loader.
  69. This provides the same functionality as built-in import. It
  70. doesn't deal with checking sys.modules -- all it provides is
  71. find_module() and a load_module(), as well as find_module_in_dir()
  72. which searches just one directory, and can be overridden by a
  73. derived class to change the module search algorithm when the basic
  74. dependency on sys.path is unchanged.
  75. The interface is a little more convenient than imp's:
  76. find_module(name, [path]) returns None or 'stuff', and
  77. load_module(name, stuff) loads the module.
  78. """
  79. def find_module(self, name, path = None):
  80. if path is None:
  81. path = [None] + self.default_path()
  82. for dir in path:
  83. stuff = self.find_module_in_dir(name, dir)
  84. if stuff: return stuff
  85. return None
  86. def default_path(self):
  87. return sys.path
  88. def find_module_in_dir(self, name, dir):
  89. if dir is None:
  90. return self.find_builtin_module(name)
  91. else:
  92. try:
  93. return imp.find_module(name, [dir])
  94. except ImportError:
  95. return None
  96. def find_builtin_module(self, name):
  97. # XXX frozen packages?
  98. if imp.is_builtin(name):
  99. return None, '', ('', '', BUILTIN_MODULE)
  100. if imp.is_frozen(name):
  101. return None, '', ('', '', FROZEN_MODULE)
  102. return None
  103. def load_module(self, name, stuff):
  104. file, filename, info = stuff
  105. try:
  106. return imp.load_module(name, file, filename, info)
  107. finally:
  108. if file: file.close()
  109. class Hooks(_Verbose):
  110. """Hooks into the filesystem and interpreter.
  111. By deriving a subclass you can redefine your filesystem interface,
  112. e.g. to merge it with the URL space.
  113. This base class behaves just like the native filesystem.
  114. """
  115. # imp interface
  116. def get_suffixes(self): return imp.get_suffixes()
  117. def new_module(self, name): return imp.new_module(name)
  118. def is_builtin(self, name): return imp.is_builtin(name)
  119. def init_builtin(self, name): return imp.init_builtin(name)
  120. def is_frozen(self, name): return imp.is_frozen(name)
  121. def init_frozen(self, name): return imp.init_frozen(name)
  122. def get_frozen_object(self, name): return imp.get_frozen_object(name)
  123. def load_source(self, name, filename, file=None):
  124. return imp.load_source(name, filename, file)
  125. def load_compiled(self, name, filename, file=None):
  126. return imp.load_compiled(name, filename, file)
  127. def load_dynamic(self, name, filename, file=None):
  128. return imp.load_dynamic(name, filename, file)
  129. def load_package(self, name, filename, file=None):
  130. return imp.load_module(name, file, filename, ("", "", PKG_DIRECTORY))
  131. def add_module(self, name):
  132. d = self.modules_dict()
  133. if name in d: return d[name]
  134. d[name] = m = self.new_module(name)
  135. return m
  136. # sys interface
  137. def modules_dict(self): return sys.modules
  138. def default_path(self): return sys.path
  139. def path_split(self, x): return os.path.split(x)
  140. def path_join(self, x, y): return os.path.join(x, y)
  141. def path_isabs(self, x): return os.path.isabs(x)
  142. # etc.
  143. def path_exists(self, x): return os.path.exists(x)
  144. def path_isdir(self, x): return os.path.isdir(x)
  145. def path_isfile(self, x): return os.path.isfile(x)
  146. def path_islink(self, x): return os.path.islink(x)
  147. # etc.
  148. def openfile(self, *x): return open(*x)
  149. openfile_error = IOError
  150. def listdir(self, x): return os.listdir(x)
  151. listdir_error = os.error
  152. # etc.
  153. class ModuleLoader(BasicModuleLoader):
  154. """Default module loader; uses file system hooks.
  155. By defining suitable hooks, you might be able to load modules from
  156. other sources than the file system, e.g. from compressed or
  157. encrypted files, tar files or (if you're brave!) URLs.
  158. """
  159. def __init__(self, hooks = None, verbose = VERBOSE):
  160. BasicModuleLoader.__init__(self, verbose)
  161. self.hooks = hooks or Hooks(verbose)
  162. def default_path(self):
  163. return self.hooks.default_path()
  164. def modules_dict(self):
  165. return self.hooks.modules_dict()
  166. def get_hooks(self):
  167. return self.hooks
  168. def set_hooks(self, hooks):
  169. self.hooks = hooks
  170. def find_builtin_module(self, name):
  171. # XXX frozen packages?
  172. if self.hooks.is_builtin(name):
  173. return None, '', ('', '', BUILTIN_MODULE)
  174. if self.hooks.is_frozen(name):
  175. return None, '', ('', '', FROZEN_MODULE)
  176. return None
  177. def find_module_in_dir(self, name, dir, allow_packages=1):
  178. if dir is None:
  179. return self.find_builtin_module(name)
  180. if allow_packages:
  181. fullname = self.hooks.path_join(dir, name)
  182. if self.hooks.path_isdir(fullname):
  183. stuff = self.find_module_in_dir("__init__", fullname, 0)
  184. if stuff:
  185. file = stuff[0]
  186. if file: file.close()
  187. return None, fullname, ('', '', PKG_DIRECTORY)
  188. for info in self.hooks.get_suffixes():
  189. suff, mode, type = info
  190. fullname = self.hooks.path_join(dir, name+suff)
  191. try:
  192. fp = self.hooks.openfile(fullname, mode)
  193. return fp, fullname, info
  194. except self.hooks.openfile_error:
  195. pass
  196. return None
  197. def load_module(self, name, stuff):
  198. file, filename, info = stuff
  199. (suff, mode, type) = info
  200. try:
  201. if type == BUILTIN_MODULE:
  202. return self.hooks.init_builtin(name)
  203. if type == FROZEN_MODULE:
  204. return self.hooks.init_frozen(name)
  205. if type == C_EXTENSION:
  206. m = self.hooks.load_dynamic(name, filename, file)
  207. elif type == PY_SOURCE:
  208. m = self.hooks.load_source(name, filename, file)
  209. elif type == PY_COMPILED:
  210. m = self.hooks.load_compiled(name, filename, file)
  211. elif type == PKG_DIRECTORY:
  212. m = self.hooks.load_package(name, filename, file)
  213. else:
  214. raise ImportError, "Unrecognized module type (%r) for %s" % \
  215. (type, name)
  216. finally:
  217. if file: file.close()
  218. m.__file__ = filename
  219. return m
  220. class FancyModuleLoader(ModuleLoader):
  221. """Fancy module loader -- parses and execs the code itself."""
  222. def load_module(self, name, stuff):
  223. file, filename, (suff, mode, type) = stuff
  224. realfilename = filename
  225. path = None
  226. if type == PKG_DIRECTORY:
  227. initstuff = self.find_module_in_dir("__init__", filename, 0)
  228. if not initstuff:
  229. raise ImportError, "No __init__ module in package %s" % name
  230. initfile, initfilename, initinfo = initstuff
  231. initsuff, initmode, inittype = initinfo
  232. if inittype not in (PY_COMPILED, PY_SOURCE):
  233. if initfile: initfile.close()
  234. raise ImportError, \
  235. "Bad type (%r) for __init__ module in package %s" % (
  236. inittype, name)
  237. path = [filename]
  238. file = initfile
  239. realfilename = initfilename
  240. type = inittype
  241. if type == FROZEN_MODULE:
  242. code = self.hooks.get_frozen_object(name)
  243. elif type == PY_COMPILED:
  244. import marshal
  245. file.seek(8)
  246. code = marshal.load(file)
  247. elif type == PY_SOURCE:
  248. data = file.read()
  249. code = compile(data, realfilename, 'exec')
  250. else:
  251. return ModuleLoader.load_module(self, name, stuff)
  252. m = self.hooks.add_module(name)
  253. if path:
  254. m.__path__ = path
  255. m.__file__ = filename
  256. try:
  257. exec code in m.__dict__
  258. except:
  259. d = self.hooks.modules_dict()
  260. if name in d:
  261. del d[name]
  262. raise
  263. return m
  264. class BasicModuleImporter(_Verbose):
  265. """Basic module importer; uses module loader.
  266. This provides basic import facilities but no package imports.
  267. """
  268. def __init__(self, loader = None, verbose = VERBOSE):
  269. _Verbose.__init__(self, verbose)
  270. self.loader = loader or ModuleLoader(None, verbose)
  271. self.modules = self.loader.modules_dict()
  272. def get_loader(self):
  273. return self.loader
  274. def set_loader(self, loader):
  275. self.loader = loader
  276. def get_hooks(self):
  277. return self.loader.get_hooks()
  278. def set_hooks(self, hooks):
  279. return self.loader.set_hooks(hooks)
  280. def import_module(self, name, globals={}, locals={}, fromlist=[]):
  281. name = str(name)
  282. if name in self.modules:
  283. return self.modules[name] # Fast path
  284. stuff = self.loader.find_module(name)
  285. if not stuff:
  286. raise ImportError, "No module named %s" % name
  287. return self.loader.load_module(name, stuff)
  288. def reload(self, module, path = None):
  289. name = str(module.__name__)
  290. stuff = self.loader.find_module(name, path)
  291. if not stuff:
  292. raise ImportError, "Module %s not found for reload" % name
  293. return self.loader.load_module(name, stuff)
  294. def unload(self, module):
  295. del self.modules[str(module.__name__)]
  296. # XXX Should this try to clear the module's namespace?
  297. def install(self):
  298. self.save_import_module = __builtin__.__import__
  299. self.save_reload = __builtin__.reload
  300. if not hasattr(__builtin__, 'unload'):
  301. __builtin__.unload = None
  302. self.save_unload = __builtin__.unload
  303. __builtin__.__import__ = self.import_module
  304. __builtin__.reload = self.reload
  305. __builtin__.unload = self.unload
  306. def uninstall(self):
  307. __builtin__.__import__ = self.save_import_module
  308. __builtin__.reload = self.save_reload
  309. __builtin__.unload = self.save_unload
  310. if not __builtin__.unload:
  311. del __builtin__.unload
  312. class ModuleImporter(BasicModuleImporter):
  313. """A module importer that supports packages."""
  314. def import_module(self, name, globals=None, locals=None, fromlist=None):
  315. parent = self.determine_parent(globals)
  316. q, tail = self.find_head_package(parent, str(name))
  317. m = self.load_tail(q, tail)
  318. if not fromlist:
  319. return q
  320. if hasattr(m, "__path__"):
  321. self.ensure_fromlist(m, fromlist)
  322. return m
  323. def determine_parent(self, globals):
  324. if not globals or not "__name__" in globals:
  325. return None
  326. pname = globals['__name__']
  327. if "__path__" in globals:
  328. parent = self.modules[pname]
  329. assert globals is parent.__dict__
  330. return parent
  331. if '.' in pname:
  332. i = pname.rfind('.')
  333. pname = pname[:i]
  334. parent = self.modules[pname]
  335. assert parent.__name__ == pname
  336. return parent
  337. return None
  338. def find_head_package(self, parent, name):
  339. if '.' in name:
  340. i = name.find('.')
  341. head = name[:i]
  342. tail = name[i+1:]
  343. else:
  344. head = name
  345. tail = ""
  346. if parent:
  347. qname = "%s.%s" % (parent.__name__, head)
  348. else:
  349. qname = head
  350. q = self.import_it(head, qname, parent)
  351. if q: return q, tail
  352. if parent:
  353. qname = head
  354. parent = None
  355. q = self.import_it(head, qname, parent)
  356. if q: return q, tail
  357. raise ImportError, "No module named " + qname
  358. def load_tail(self, q, tail):
  359. m = q
  360. while tail:
  361. i = tail.find('.')
  362. if i < 0: i = len(tail)
  363. head, tail = tail[:i], tail[i+1:]
  364. mname = "%s.%s" % (m.__name__, head)
  365. m = self.import_it(head, mname, m)
  366. if not m:
  367. raise ImportError, "No module named " + mname
  368. return m
  369. def ensure_fromlist(self, m, fromlist, recursive=0):
  370. for sub in fromlist:
  371. if sub == "*":
  372. if not recursive:
  373. try:
  374. all = m.__all__
  375. except AttributeError:
  376. pass
  377. else:
  378. self.ensure_fromlist(m, all, 1)
  379. continue
  380. if sub != "*" and not hasattr(m, sub):
  381. subname = "%s.%s" % (m.__name__, sub)
  382. submod = self.import_it(sub, subname, m)
  383. if not submod:
  384. raise ImportError, "No module named " + subname
  385. def import_it(self, partname, fqname, parent, force_load=0):
  386. if not partname:
  387. raise ValueError, "Empty module name"
  388. if not force_load:
  389. try:
  390. return self.modules[fqname]
  391. except KeyError:
  392. pass
  393. try:
  394. path = parent and parent.__path__
  395. except AttributeError:
  396. return None
  397. partname = str(partname)
  398. stuff = self.loader.find_module(partname, path)
  399. if not stuff:
  400. return None
  401. fqname = str(fqname)
  402. m = self.loader.load_module(fqname, stuff)
  403. if parent:
  404. setattr(parent, partname, m)
  405. return m
  406. def reload(self, module):
  407. name = str(module.__name__)
  408. if '.' not in name:
  409. return self.import_it(name, name, None, force_load=1)
  410. i = name.rfind('.')
  411. pname = name[:i]
  412. parent = self.modules[pname]
  413. return self.import_it(name[i+1:], name, parent, force_load=1)
  414. default_importer = None
  415. current_importer = None
  416. def install(importer = None):
  417. global current_importer
  418. current_importer = importer or default_importer or ModuleImporter()
  419. current_importer.install()
  420. def uninstall():
  421. global current_importer
  422. current_importer.uninstall()