blob: d2eabc4cdd9fe0162bf14945e68b18388a575a25 [file] [log] [blame]
Guido van Rossume7e578f1995-08-04 04:00:20 +00001"""Import hook support.
2
3Consistent use of this module will make it possible to change the
4different mechanisms involved in loading modules independently.
5
6While the built-in module imp exports interfaces to the built-in
7module searching and loading algorithm, and it is possible to replace
8the built-in function __import__ in order to change the semantics of
9the import statement, until now it has been difficult to combine the
10effect of different __import__ hacks, like loading modules from URLs
Guido van Rossuma8add0e2007-05-14 22:03:55 +000011by rimport.py.
Guido van Rossume7e578f1995-08-04 04:00:20 +000012
13This module defines three new concepts:
14
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000151) A "file system hooks" class provides an interface to a filesystem.
Guido van Rossume7e578f1995-08-04 04:00:20 +000016
17One hooks class is defined (Hooks), which uses the interface provided
18by standard modules os and os.path. It should be used as the base
19class for other hooks classes.
20
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000212) A "module loader" class provides an interface to search for a
Guido van Rossume7e578f1995-08-04 04:00:20 +000022module in a search path and to load it. It defines a method which
23searches for a module in a single directory; by overriding this method
24one can redefine the details of the search. If the directory is None,
25built-in and frozen modules are searched instead.
26
27Two module loader class are defined, both implementing the search
28strategy used by the built-in __import__ function: ModuleLoader uses
29the imp module's find_module interface, while HookableModuleLoader
30uses a file system hooks class to interact with the file system. Both
31use the imp module's load_* interfaces to actually load the module.
32
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000333) A "module importer" class provides an interface to import a
Guido van Rossume7e578f1995-08-04 04:00:20 +000034module, as well as interfaces to reload and unload a module. It also
35provides interfaces to install and uninstall itself instead of the
36default __import__ and reload (and unload) functions.
37
38One module importer class is defined (ModuleImporter), which uses a
39module loader instance passed in (by default HookableModuleLoader is
40instantiated).
41
42The classes defined here should be used as base classes for extended
43functionality along those lines.
44
Skip Montanaro2dd42762001-01-23 15:35:05 +000045If a module importer class supports dotted names, its import_module()
Guido van Rossume7e578f1995-08-04 04:00:20 +000046must return a different value depending on whether it is called on
47behalf of a "from ... import ..." statement or not. (This is caused
Guido van Rossume7ba4952007-06-06 23:52:48 +000048by the way the __import__ hook is used by the Python interpreter.)
Guido van Rossume7e578f1995-08-04 04:00:20 +000049"""
50
51
52import __builtin__
53import imp
54import os
55import sys
Guido van Rossum9f5c36f1998-06-29 20:31:16 +000056
Skip Montanaro2dd42762001-01-23 15:35:05 +000057__all__ = ["BasicModuleLoader","Hooks","ModuleLoader","FancyModuleLoader",
58 "BasicModuleImporter","ModuleImporter","install","uninstall"]
Guido van Rossum9f5c36f1998-06-29 20:31:16 +000059
60VERBOSE = 0
Guido van Rossume7e578f1995-08-04 04:00:20 +000061
62
63from imp import C_EXTENSION, PY_SOURCE, PY_COMPILED
Guido van Rossum9f5c36f1998-06-29 20:31:16 +000064from imp import C_BUILTIN, PY_FROZEN, PKG_DIRECTORY
65BUILTIN_MODULE = C_BUILTIN
66FROZEN_MODULE = PY_FROZEN
Guido van Rossume7e578f1995-08-04 04:00:20 +000067
68
69class _Verbose:
70
Guido van Rossum9f5c36f1998-06-29 20:31:16 +000071 def __init__(self, verbose = VERBOSE):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000072 self.verbose = verbose
Guido van Rossume7e578f1995-08-04 04:00:20 +000073
74 def get_verbose(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000075 return self.verbose
Guido van Rossume7e578f1995-08-04 04:00:20 +000076
77 def set_verbose(self, verbose):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000078 self.verbose = verbose
Guido van Rossume7e578f1995-08-04 04:00:20 +000079
80 # XXX The following is an experimental interface
81
82 def note(self, *args):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000083 if self.verbose:
Guido van Rossum68468eb2003-02-27 20:14:51 +000084 self.message(*args)
Guido van Rossume7e578f1995-08-04 04:00:20 +000085
86 def message(self, format, *args):
Guido van Rossum9f5c36f1998-06-29 20:31:16 +000087 if args:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000088 print(format%args)
Guido van Rossum9f5c36f1998-06-29 20:31:16 +000089 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000090 print(format)
Guido van Rossume7e578f1995-08-04 04:00:20 +000091
92
93class BasicModuleLoader(_Verbose):
94
95 """Basic module loader.
96
97 This provides the same functionality as built-in import. It
98 doesn't deal with checking sys.modules -- all it provides is
99 find_module() and a load_module(), as well as find_module_in_dir()
100 which searches just one directory, and can be overridden by a
101 derived class to change the module search algorithm when the basic
102 dependency on sys.path is unchanged.
103
104 The interface is a little more convenient than imp's:
105 find_module(name, [path]) returns None or 'stuff', and
106 load_module(name, stuff) loads the module.
107
108 """
109
110 def find_module(self, name, path = None):
Tim Peters07e99cb2001-01-14 23:47:14 +0000111 if path is None:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000112 path = [None] + self.default_path()
113 for dir in path:
114 stuff = self.find_module_in_dir(name, dir)
115 if stuff: return stuff
116 return None
Guido van Rossume7e578f1995-08-04 04:00:20 +0000117
118 def default_path(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000119 return sys.path
Guido van Rossume7e578f1995-08-04 04:00:20 +0000120
121 def find_module_in_dir(self, name, dir):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000122 if dir is None:
123 return self.find_builtin_module(name)
124 else:
125 try:
126 return imp.find_module(name, [dir])
127 except ImportError:
128 return None
Guido van Rossume7e578f1995-08-04 04:00:20 +0000129
130 def find_builtin_module(self, name):
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000131 # XXX frozen packages?
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000132 if imp.is_builtin(name):
133 return None, '', ('', '', BUILTIN_MODULE)
134 if imp.is_frozen(name):
135 return None, '', ('', '', FROZEN_MODULE)
136 return None
Guido van Rossume7e578f1995-08-04 04:00:20 +0000137
138 def load_module(self, name, stuff):
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000139 file, filename, info = stuff
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000140 try:
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000141 return imp.load_module(name, file, filename, info)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000142 finally:
143 if file: file.close()
Guido van Rossume7e578f1995-08-04 04:00:20 +0000144
145
146class Hooks(_Verbose):
147
148 """Hooks into the filesystem and interpreter.
149
150 By deriving a subclass you can redefine your filesystem interface,
151 e.g. to merge it with the URL space.
152
153 This base class behaves just like the native filesystem.
154
155 """
156
157 # imp interface
158 def get_suffixes(self): return imp.get_suffixes()
159 def new_module(self, name): return imp.new_module(name)
160 def is_builtin(self, name): return imp.is_builtin(name)
161 def init_builtin(self, name): return imp.init_builtin(name)
162 def is_frozen(self, name): return imp.is_frozen(name)
163 def init_frozen(self, name): return imp.init_frozen(name)
164 def get_frozen_object(self, name): return imp.get_frozen_object(name)
165 def load_source(self, name, filename, file=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000166 return imp.load_source(name, filename, file)
Guido van Rossume7e578f1995-08-04 04:00:20 +0000167 def load_compiled(self, name, filename, file=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000168 return imp.load_compiled(name, filename, file)
Guido van Rossume7e578f1995-08-04 04:00:20 +0000169 def load_dynamic(self, name, filename, file=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000170 return imp.load_dynamic(name, filename, file)
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000171 def load_package(self, name, filename, file=None):
172 return imp.load_module(name, file, filename, ("", "", PKG_DIRECTORY))
Guido van Rossume7e578f1995-08-04 04:00:20 +0000173
174 def add_module(self, name):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000175 d = self.modules_dict()
Raymond Hettinger54f02222002-06-01 14:18:47 +0000176 if name in d: return d[name]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000177 d[name] = m = self.new_module(name)
178 return m
Guido van Rossume7e578f1995-08-04 04:00:20 +0000179
180 # sys interface
181 def modules_dict(self): return sys.modules
182 def default_path(self): return sys.path
183
184 def path_split(self, x): return os.path.split(x)
185 def path_join(self, x, y): return os.path.join(x, y)
186 def path_isabs(self, x): return os.path.isabs(x)
187 # etc.
188
189 def path_exists(self, x): return os.path.exists(x)
190 def path_isdir(self, x): return os.path.isdir(x)
191 def path_isfile(self, x): return os.path.isfile(x)
192 def path_islink(self, x): return os.path.islink(x)
193 # etc.
194
Guido van Rossum68468eb2003-02-27 20:14:51 +0000195 def openfile(self, *x): return open(*x)
Guido van Rossume7e578f1995-08-04 04:00:20 +0000196 openfile_error = IOError
197 def listdir(self, x): return os.listdir(x)
198 listdir_error = os.error
199 # etc.
200
201
202class ModuleLoader(BasicModuleLoader):
203
204 """Default module loader; uses file system hooks.
205
206 By defining suitable hooks, you might be able to load modules from
207 other sources than the file system, e.g. from compressed or
208 encrypted files, tar files or (if you're brave!) URLs.
209
210 """
211
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000212 def __init__(self, hooks = None, verbose = VERBOSE):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000213 BasicModuleLoader.__init__(self, verbose)
214 self.hooks = hooks or Hooks(verbose)
Guido van Rossume7e578f1995-08-04 04:00:20 +0000215
216 def default_path(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000217 return self.hooks.default_path()
Guido van Rossume7e578f1995-08-04 04:00:20 +0000218
219 def modules_dict(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000220 return self.hooks.modules_dict()
Guido van Rossume7e578f1995-08-04 04:00:20 +0000221
222 def get_hooks(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000223 return self.hooks
Guido van Rossume7e578f1995-08-04 04:00:20 +0000224
225 def set_hooks(self, hooks):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000226 self.hooks = hooks
Guido van Rossume7e578f1995-08-04 04:00:20 +0000227
228 def find_builtin_module(self, name):
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000229 # XXX frozen packages?
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000230 if self.hooks.is_builtin(name):
231 return None, '', ('', '', BUILTIN_MODULE)
232 if self.hooks.is_frozen(name):
233 return None, '', ('', '', FROZEN_MODULE)
234 return None
Guido van Rossume7e578f1995-08-04 04:00:20 +0000235
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000236 def find_module_in_dir(self, name, dir, allow_packages=1):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000237 if dir is None:
238 return self.find_builtin_module(name)
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000239 if allow_packages:
240 fullname = self.hooks.path_join(dir, name)
241 if self.hooks.path_isdir(fullname):
242 stuff = self.find_module_in_dir("__init__", fullname, 0)
243 if stuff:
244 file = stuff[0]
245 if file: file.close()
246 return None, fullname, ('', '', PKG_DIRECTORY)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000247 for info in self.hooks.get_suffixes():
248 suff, mode, type = info
249 fullname = self.hooks.path_join(dir, name+suff)
250 try:
251 fp = self.hooks.openfile(fullname, mode)
252 return fp, fullname, info
253 except self.hooks.openfile_error:
254 pass
255 return None
Guido van Rossume7e578f1995-08-04 04:00:20 +0000256
257 def load_module(self, name, stuff):
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000258 file, filename, info = stuff
259 (suff, mode, type) = info
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000260 try:
261 if type == BUILTIN_MODULE:
262 return self.hooks.init_builtin(name)
263 if type == FROZEN_MODULE:
264 return self.hooks.init_frozen(name)
265 if type == C_EXTENSION:
266 m = self.hooks.load_dynamic(name, filename, file)
267 elif type == PY_SOURCE:
268 m = self.hooks.load_source(name, filename, file)
269 elif type == PY_COMPILED:
270 m = self.hooks.load_compiled(name, filename, file)
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000271 elif type == PKG_DIRECTORY:
272 m = self.hooks.load_package(name, filename, file)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000273 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000274 raise ImportError("Unrecognized module type (%r) for %s"
275 % (type, name))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000276 finally:
277 if file: file.close()
278 m.__file__ = filename
279 return m
Guido van Rossume7e578f1995-08-04 04:00:20 +0000280
281
282class FancyModuleLoader(ModuleLoader):
283
284 """Fancy module loader -- parses and execs the code itself."""
285
286 def load_module(self, name, stuff):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000287 file, filename, (suff, mode, type) = stuff
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000288 realfilename = filename
289 path = None
290
291 if type == PKG_DIRECTORY:
292 initstuff = self.find_module_in_dir("__init__", filename, 0)
293 if not initstuff:
Collin Winterce36ad82007-08-30 01:19:48 +0000294 raise ImportError("No __init__ module in package %s" % name)
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000295 initfile, initfilename, initinfo = initstuff
296 initsuff, initmode, inittype = initinfo
297 if inittype not in (PY_COMPILED, PY_SOURCE):
298 if initfile: initfile.close()
Collin Winterce36ad82007-08-30 01:19:48 +0000299 raise ImportError("Bad type (%r) for __init__ module"
300 " in package %s" % (inittype, name))
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000301 path = [filename]
302 file = initfile
303 realfilename = initfilename
304 type = inittype
305
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000306 if type == FROZEN_MODULE:
307 code = self.hooks.get_frozen_object(name)
308 elif type == PY_COMPILED:
309 import marshal
310 file.seek(8)
311 code = marshal.load(file)
312 elif type == PY_SOURCE:
313 data = file.read()
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000314 code = compile(data, realfilename, 'exec')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000315 else:
316 return ModuleLoader.load_module(self, name, stuff)
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000317
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000318 m = self.hooks.add_module(name)
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000319 if path:
320 m.__path__ = path
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000321 m.__file__ = filename
Tim Peters3d3cfdb2004-08-04 02:29:12 +0000322 try:
Georg Brandl7cae87c2006-09-06 06:51:57 +0000323 exec(code, m.__dict__)
Tim Peters3d3cfdb2004-08-04 02:29:12 +0000324 except:
325 d = self.hooks.modules_dict()
326 if name in d:
327 del d[name]
328 raise
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000329 return m
Guido van Rossume7e578f1995-08-04 04:00:20 +0000330
331
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000332class BasicModuleImporter(_Verbose):
Guido van Rossume7e578f1995-08-04 04:00:20 +0000333
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000334 """Basic module importer; uses module loader.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000335
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000336 This provides basic import facilities but no package imports.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000337
338 """
339
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000340 def __init__(self, loader = None, verbose = VERBOSE):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000341 _Verbose.__init__(self, verbose)
342 self.loader = loader or ModuleLoader(None, verbose)
343 self.modules = self.loader.modules_dict()
Guido van Rossume7e578f1995-08-04 04:00:20 +0000344
345 def get_loader(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000346 return self.loader
Guido van Rossume7e578f1995-08-04 04:00:20 +0000347
348 def set_loader(self, loader):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000349 self.loader = loader
Guido van Rossume7e578f1995-08-04 04:00:20 +0000350
351 def get_hooks(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000352 return self.loader.get_hooks()
Guido van Rossume7e578f1995-08-04 04:00:20 +0000353
354 def set_hooks(self, hooks):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000355 return self.loader.set_hooks(hooks)
Guido van Rossume7e578f1995-08-04 04:00:20 +0000356
357 def import_module(self, name, globals={}, locals={}, fromlist=[]):
Gustavo Niemeyerd5ae01a2002-12-16 13:11:57 +0000358 name = str(name)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000359 if name in self.modules:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000360 return self.modules[name] # Fast path
361 stuff = self.loader.find_module(name)
362 if not stuff:
Collin Winterce36ad82007-08-30 01:19:48 +0000363 raise ImportError("No module named %s" % name)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000364 return self.loader.load_module(name, stuff)
Guido van Rossume7e578f1995-08-04 04:00:20 +0000365
366 def reload(self, module, path = None):
Gustavo Niemeyerd5ae01a2002-12-16 13:11:57 +0000367 name = str(module.__name__)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000368 stuff = self.loader.find_module(name, path)
369 if not stuff:
Collin Winterce36ad82007-08-30 01:19:48 +0000370 raise ImportError("Module %s not found for reload" % name)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000371 return self.loader.load_module(name, stuff)
Guido van Rossume7e578f1995-08-04 04:00:20 +0000372
373 def unload(self, module):
Gustavo Niemeyerd5ae01a2002-12-16 13:11:57 +0000374 del self.modules[str(module.__name__)]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000375 # XXX Should this try to clear the module's namespace?
Guido van Rossume7e578f1995-08-04 04:00:20 +0000376
377 def install(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000378 self.save_import_module = __builtin__.__import__
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000379 if not hasattr(__builtin__, 'unload'):
380 __builtin__.unload = None
381 self.save_unload = __builtin__.unload
382 __builtin__.__import__ = self.import_module
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000383 __builtin__.unload = self.unload
Guido van Rossume7e578f1995-08-04 04:00:20 +0000384
385 def uninstall(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000386 __builtin__.__import__ = self.save_import_module
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000387 __builtin__.unload = self.save_unload
388 if not __builtin__.unload:
389 del __builtin__.unload
Guido van Rossume7e578f1995-08-04 04:00:20 +0000390
391
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000392class ModuleImporter(BasicModuleImporter):
393
394 """A module importer that supports packages."""
Tim Peters07e99cb2001-01-14 23:47:14 +0000395
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000396 def import_module(self, name, globals=None, locals=None, fromlist=None):
397 parent = self.determine_parent(globals)
Gustavo Niemeyerd5ae01a2002-12-16 13:11:57 +0000398 q, tail = self.find_head_package(parent, str(name))
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000399 m = self.load_tail(q, tail)
400 if not fromlist:
401 return q
402 if hasattr(m, "__path__"):
403 self.ensure_fromlist(m, fromlist)
404 return m
405
406 def determine_parent(self, globals):
Raymond Hettinger54f02222002-06-01 14:18:47 +0000407 if not globals or not "__name__" in globals:
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000408 return None
409 pname = globals['__name__']
Raymond Hettinger54f02222002-06-01 14:18:47 +0000410 if "__path__" in globals:
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000411 parent = self.modules[pname]
412 assert globals is parent.__dict__
413 return parent
414 if '.' in pname:
Eric S. Raymondbf97c9d2001-02-09 10:18:37 +0000415 i = pname.rfind('.')
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000416 pname = pname[:i]
417 parent = self.modules[pname]
418 assert parent.__name__ == pname
419 return parent
420 return None
421
422 def find_head_package(self, parent, name):
423 if '.' in name:
Eric S. Raymondbf97c9d2001-02-09 10:18:37 +0000424 i = name.find('.')
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000425 head = name[:i]
426 tail = name[i+1:]
427 else:
428 head = name
429 tail = ""
430 if parent:
431 qname = "%s.%s" % (parent.__name__, head)
432 else:
433 qname = head
434 q = self.import_it(head, qname, parent)
435 if q: return q, tail
436 if parent:
437 qname = head
438 parent = None
439 q = self.import_it(head, qname, parent)
440 if q: return q, tail
Collin Winterce36ad82007-08-30 01:19:48 +0000441 raise ImportError("No module named " + qname)
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000442
443 def load_tail(self, q, tail):
444 m = q
445 while tail:
Eric S. Raymondbf97c9d2001-02-09 10:18:37 +0000446 i = tail.find('.')
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000447 if i < 0: i = len(tail)
448 head, tail = tail[:i], tail[i+1:]
449 mname = "%s.%s" % (m.__name__, head)
450 m = self.import_it(head, mname, m)
451 if not m:
Collin Winterce36ad82007-08-30 01:19:48 +0000452 raise ImportError("No module named " + mname)
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000453 return m
454
455 def ensure_fromlist(self, m, fromlist, recursive=0):
456 for sub in fromlist:
457 if sub == "*":
458 if not recursive:
459 try:
460 all = m.__all__
461 except AttributeError:
462 pass
463 else:
464 self.ensure_fromlist(m, all, 1)
465 continue
466 if sub != "*" and not hasattr(m, sub):
467 subname = "%s.%s" % (m.__name__, sub)
468 submod = self.import_it(sub, subname, m)
469 if not submod:
Collin Winterce36ad82007-08-30 01:19:48 +0000470 raise ImportError("No module named " + subname)
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000471
Fred Drake8deeced2000-04-13 14:52:27 +0000472 def import_it(self, partname, fqname, parent, force_load=0):
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000473 if not partname:
Collin Winterce36ad82007-08-30 01:19:48 +0000474 raise ValueError("Empty module name")
Fred Drake8deeced2000-04-13 14:52:27 +0000475 if not force_load:
476 try:
477 return self.modules[fqname]
478 except KeyError:
479 pass
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000480 try:
481 path = parent and parent.__path__
482 except AttributeError:
483 return None
Gustavo Niemeyerd5ae01a2002-12-16 13:11:57 +0000484 partname = str(partname)
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000485 stuff = self.loader.find_module(partname, path)
486 if not stuff:
487 return None
Gustavo Niemeyerd5ae01a2002-12-16 13:11:57 +0000488 fqname = str(fqname)
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000489 m = self.loader.load_module(fqname, stuff)
490 if parent:
491 setattr(parent, partname, m)
492 return m
493
494 def reload(self, module):
Gustavo Niemeyerd5ae01a2002-12-16 13:11:57 +0000495 name = str(module.__name__)
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000496 if '.' not in name:
Fred Drake8deeced2000-04-13 14:52:27 +0000497 return self.import_it(name, name, None, force_load=1)
Eric S. Raymondbf97c9d2001-02-09 10:18:37 +0000498 i = name.rfind('.')
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000499 pname = name[:i]
500 parent = self.modules[pname]
Fred Drake8deeced2000-04-13 14:52:27 +0000501 return self.import_it(name[i+1:], name, parent, force_load=1)
Guido van Rossum9f5c36f1998-06-29 20:31:16 +0000502
503
Guido van Rossume7e578f1995-08-04 04:00:20 +0000504default_importer = None
505current_importer = None
506
507def install(importer = None):
508 global current_importer
509 current_importer = importer or default_importer or ModuleImporter()
510 current_importer.install()
511
512def uninstall():
513 global current_importer
514 current_importer.uninstall()