blob: a0099a86e86591f537a68fb0a39938b401a63666 [file] [log] [blame]
Fred Drake05857df2001-09-04 18:39:45 +00001"""
2Import utilities
Greg Stein99a56212000-06-26 17:31:49 +00003
Fred Drake05857df2001-09-04 18:39:45 +00004Exported classes:
5 ImportManager Manage the import process
6
7 Importer Base class for replacing standard import functions
8 BuiltinImporter Emulate the import mechanism for builtin and frozen modules
9
10 DynLoadSuffixImporter
11"""
Greg Stein281b8d81999-11-07 12:54:45 +000012
Greg Stein281b8d81999-11-07 12:54:45 +000013# note: avoid importing non-builtin modules
Tim Peters07e99cb2001-01-14 23:47:14 +000014import imp ### not available in JPython?
Greg Stein281b8d81999-11-07 12:54:45 +000015import sys
Greg Stein7ec28d21999-11-20 12:31:07 +000016import __builtin__
Greg Stein281b8d81999-11-07 12:54:45 +000017
18# for the DirectoryImporter
19import struct
20import marshal
21
Skip Montanaro17ab1232001-01-24 06:27:27 +000022__all__ = ["ImportManager","Importer","BuiltinImporter"]
23
Greg Steinf23aa1e2000-01-03 02:38:29 +000024_StringType = type('')
Tim Peters07e99cb2001-01-14 23:47:14 +000025_ModuleType = type(sys) ### doesn't work in JPython...
Greg Steinf23aa1e2000-01-03 02:38:29 +000026
27class ImportManager:
Greg Steindd6eefb2000-07-18 09:09:48 +000028 "Manage the import process."
Greg Stein281b8d81999-11-07 12:54:45 +000029
Greg Steindd6eefb2000-07-18 09:09:48 +000030 def install(self, namespace=vars(__builtin__)):
31 "Install this ImportManager into the specified namespace."
Greg Steind4f1d202000-02-18 12:03:40 +000032
Greg Steindd6eefb2000-07-18 09:09:48 +000033 if isinstance(namespace, _ModuleType):
34 namespace = vars(namespace)
Greg Steind4f1d202000-02-18 12:03:40 +000035
Greg Stein76977bb2001-04-07 16:05:24 +000036 # Note: we have no notion of "chaining"
Greg Stein3bb578c2000-02-18 13:04:10 +000037
Greg Stein76977bb2001-04-07 16:05:24 +000038 # Record the previous import hook, then install our own.
39 self.previous_importer = namespace['__import__']
40 self.namespace = namespace
Greg Steindd6eefb2000-07-18 09:09:48 +000041 namespace['__import__'] = self._import_hook
Greg Stein76977bb2001-04-07 16:05:24 +000042
Greg Stein76977bb2001-04-07 16:05:24 +000043 def uninstall(self):
44 "Restore the previous import mechanism."
45 self.namespace['__import__'] = self.previous_importer
46
Greg Steindd6eefb2000-07-18 09:09:48 +000047 def add_suffix(self, suffix, importFunc):
Guido van Rossumd59da4b2007-05-22 18:11:13 +000048 assert hasattr(importFunc, '__call__')
Greg Steindd6eefb2000-07-18 09:09:48 +000049 self.fs_imp.add_suffix(suffix, importFunc)
Greg Stein281b8d81999-11-07 12:54:45 +000050
Greg Steindd6eefb2000-07-18 09:09:48 +000051 ######################################################################
52 #
53 # PRIVATE METHODS
54 #
Greg Stein3bb578c2000-02-18 13:04:10 +000055
Greg Steindd6eefb2000-07-18 09:09:48 +000056 clsFilesystemImporter = None
Greg Stein281b8d81999-11-07 12:54:45 +000057
Greg Steindd6eefb2000-07-18 09:09:48 +000058 def __init__(self, fs_imp=None):
59 # we're definitely going to be importing something in the future,
60 # so let's just load the OS-related facilities.
61 if not _os_stat:
62 _os_bootstrap()
Greg Stein3bb578c2000-02-18 13:04:10 +000063
Greg Steindd6eefb2000-07-18 09:09:48 +000064 # This is the Importer that we use for grabbing stuff from the
65 # filesystem. It defines one more method (import_from_dir) for our use.
Raymond Hettinger936654b2002-06-01 03:06:31 +000066 if fs_imp is None:
Greg Steindd6eefb2000-07-18 09:09:48 +000067 cls = self.clsFilesystemImporter or _FilesystemImporter
68 fs_imp = cls()
69 self.fs_imp = fs_imp
Greg Stein281b8d81999-11-07 12:54:45 +000070
Greg Steindd6eefb2000-07-18 09:09:48 +000071 # Initialize the set of suffixes that we recognize and import.
72 # The default will import dynamic-load modules first, followed by
73 # .py files (or a .py file's cached bytecode)
74 for desc in imp.get_suffixes():
75 if desc[2] == imp.C_EXTENSION:
76 self.add_suffix(desc[0],
77 DynLoadSuffixImporter(desc).import_file)
78 self.add_suffix('.py', py_suffix_importer)
Greg Steinf23aa1e2000-01-03 02:38:29 +000079
Greg Steindd6eefb2000-07-18 09:09:48 +000080 def _import_hook(self, fqname, globals=None, locals=None, fromlist=None):
81 """Python calls this hook to locate and import a module."""
Greg Stein63faa011999-11-20 11:22:37 +000082
Martin v. Löwisd3011cd2001-07-28 17:59:34 +000083 parts = fqname.split('.')
Greg Stein281b8d81999-11-07 12:54:45 +000084
Greg Steindd6eefb2000-07-18 09:09:48 +000085 # determine the context of this import
86 parent = self._determine_import_context(globals)
Greg Stein281b8d81999-11-07 12:54:45 +000087
Greg Steindd6eefb2000-07-18 09:09:48 +000088 # if there is a parent, then its importer should manage this import
89 if parent:
90 module = parent.__importer__._do_import(parent, parts, fromlist)
91 if module:
92 return module
Greg Stein281b8d81999-11-07 12:54:45 +000093
Greg Steindd6eefb2000-07-18 09:09:48 +000094 # has the top module already been imported?
95 try:
96 top_module = sys.modules[parts[0]]
97 except KeyError:
98
99 # look for the topmost module
100 top_module = self._import_top_module(parts[0])
101 if not top_module:
102 # the topmost module wasn't found at all.
103 raise ImportError, 'No module named ' + fqname
104
105 # fast-path simple imports
106 if len(parts) == 1:
107 if not fromlist:
108 return top_module
109
110 if not top_module.__dict__.get('__ispkg__'):
111 # __ispkg__ isn't defined (the module was not imported by us),
112 # or it is zero.
113 #
114 # In the former case, there is no way that we could import
115 # sub-modules that occur in the fromlist (but we can't raise an
116 # error because it may just be names) because we don't know how
117 # to deal with packages that were imported by other systems.
118 #
119 # In the latter case (__ispkg__ == 0), there can't be any sub-
120 # modules present, so we can just return.
121 #
122 # In both cases, since len(parts) == 1, the top_module is also
123 # the "bottom" which is the defined return when a fromlist
124 # exists.
125 return top_module
126
127 importer = top_module.__dict__.get('__importer__')
128 if importer:
129 return importer._finish_import(top_module, parts[1:], fromlist)
130
Thomas Wouters477c8d52006-05-27 19:21:47 +0000131 # Grrr, some people "import os.path" or do "from os.path import ..."
Martin v. Löwis70195da2001-07-28 20:33:41 +0000132 if len(parts) == 2 and hasattr(top_module, parts[1]):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000133 if fromlist:
134 return getattr(top_module, parts[1])
135 else:
136 return top_module
Martin v. Löwis70195da2001-07-28 20:33:41 +0000137
Greg Steindd6eefb2000-07-18 09:09:48 +0000138 # If the importer does not exist, then we have to bail. A missing
139 # importer means that something else imported the module, and we have
140 # no knowledge of how to get sub-modules out of the thing.
Greg Steinf23aa1e2000-01-03 02:38:29 +0000141 raise ImportError, 'No module named ' + fqname
Greg Steinf23aa1e2000-01-03 02:38:29 +0000142
Greg Steindd6eefb2000-07-18 09:09:48 +0000143 def _determine_import_context(self, globals):
144 """Returns the context in which a module should be imported.
Greg Steinf23aa1e2000-01-03 02:38:29 +0000145
Greg Steindd6eefb2000-07-18 09:09:48 +0000146 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
149 "top-level" module.
150 """
Greg Steinf23aa1e2000-01-03 02:38:29 +0000151
Greg Steindd6eefb2000-07-18 09:09:48 +0000152 if not globals or not globals.get('__importer__'):
153 # globals does not refer to one of our modules or packages. That
154 # implies there is no relative import context (as far as we are
155 # concerned), and it should just pick it off the standard path.
156 return None
Greg Steinf23aa1e2000-01-03 02:38:29 +0000157
Greg Steindd6eefb2000-07-18 09:09:48 +0000158 # The globals refer to a module or package of ours. It will define
159 # the context of the new import. Get the module/package fqname.
160 parent_fqname = globals['__name__']
Greg Steinf23aa1e2000-01-03 02:38:29 +0000161
Greg Steindd6eefb2000-07-18 09:09:48 +0000162 # if a package is performing the import, then return itself (imports
163 # refer to pkg contents)
164 if globals['__ispkg__']:
165 parent = sys.modules[parent_fqname]
166 assert globals is parent.__dict__
167 return parent
Greg Steinf23aa1e2000-01-03 02:38:29 +0000168
Martin v. Löwisd3011cd2001-07-28 17:59:34 +0000169 i = parent_fqname.rfind('.')
Greg Steinf23aa1e2000-01-03 02:38:29 +0000170
Greg Steindd6eefb2000-07-18 09:09:48 +0000171 # a module outside of a package has no particular import context
172 if i == -1:
173 return None
Greg Steinf23aa1e2000-01-03 02:38:29 +0000174
Greg Steindd6eefb2000-07-18 09:09:48 +0000175 # if a module in a package is performing the import, then return the
176 # package (imports refer to siblings)
177 parent_fqname = parent_fqname[:i]
178 parent = sys.modules[parent_fqname]
179 assert parent.__name__ == parent_fqname
180 return parent
Greg Steinf23aa1e2000-01-03 02:38:29 +0000181
Greg Steindd6eefb2000-07-18 09:09:48 +0000182 def _import_top_module(self, name):
183 # scan sys.path looking for a location in the filesystem that contains
184 # the module, or an Importer object that can import the module.
185 for item in sys.path:
186 if isinstance(item, _StringType):
187 module = self.fs_imp.import_from_dir(item, name)
188 else:
189 module = item.import_top(name)
190 if module:
191 return module
192 return None
Greg Steinf23aa1e2000-01-03 02:38:29 +0000193
Greg Steinf23aa1e2000-01-03 02:38:29 +0000194
195class Importer:
Greg Steindd6eefb2000-07-18 09:09:48 +0000196 "Base class for replacing standard import functions."
Greg Steinf23aa1e2000-01-03 02:38:29 +0000197
Greg Steindd6eefb2000-07-18 09:09:48 +0000198 def import_top(self, name):
199 "Import a top-level module."
200 return self._import_one(None, name, name)
Greg Steinf23aa1e2000-01-03 02:38:29 +0000201
Greg Steindd6eefb2000-07-18 09:09:48 +0000202 ######################################################################
Greg Stein281b8d81999-11-07 12:54:45 +0000203 #
Greg Steindd6eefb2000-07-18 09:09:48 +0000204 # PRIVATE METHODS
Greg Stein281b8d81999-11-07 12:54:45 +0000205 #
Greg Steindd6eefb2000-07-18 09:09:48 +0000206 def _finish_import(self, top, parts, fromlist):
207 # if "a.b.c" was provided, then load the ".b.c" portion down from
208 # below the top-level module.
209 bottom = self._load_tail(top, parts)
Greg Stein281b8d81999-11-07 12:54:45 +0000210
Greg Steindd6eefb2000-07-18 09:09:48 +0000211 # if the form is "import a.b.c", then return "a"
212 if not fromlist:
213 # no fromlist: return the top of the import tree
214 return top
215
216 # the top module was imported by self.
217 #
218 # this means that the bottom module was also imported by self (just
219 # now, or in the past and we fetched it from sys.modules).
220 #
221 # since we imported/handled the bottom module, this means that we can
222 # also handle its fromlist (and reliably use __ispkg__).
223
224 # if the bottom node is a package, then (potentially) import some
225 # modules.
226 #
227 # note: if it is not a package, then "fromlist" refers to names in
228 # the bottom module rather than modules.
229 # note: for a mix of names and modules in the fromlist, we will
230 # import all modules and insert those into the namespace of
231 # the package module. Python will pick up all fromlist names
232 # from the bottom (package) module; some will be modules that
233 # we imported and stored in the namespace, others are expected
234 # to be present already.
235 if bottom.__ispkg__:
236 self._import_fromlist(bottom, fromlist)
237
238 # if the form is "from a.b import c, d" then return "b"
239 return bottom
240
241 def _import_one(self, parent, modname, fqname):
242 "Import a single module."
243
244 # has the module already been imported?
245 try:
246 return sys.modules[fqname]
247 except KeyError:
248 pass
249
250 # load the module's code, or fetch the module itself
251 result = self.get_code(parent, modname, fqname)
252 if result is None:
253 return None
254
255 module = self._process_result(result, fqname)
256
257 # insert the module into its parent
258 if parent:
259 setattr(parent, modname, module)
260 return module
261
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000262 def _process_result(self, result, fqname):
263 # unpack result
264 ispkg, code, values = result
265
Greg Steindd6eefb2000-07-18 09:09:48 +0000266 # did get_code() return an actual module? (rather than a code object)
267 is_module = isinstance(code, _ModuleType)
268
269 # use the returned module, or create a new one to exec code into
270 if is_module:
271 module = code
272 else:
273 module = imp.new_module(fqname)
274
275 ### record packages a bit differently??
276 module.__importer__ = self
277 module.__ispkg__ = ispkg
278
279 # insert additional values into the module (before executing the code)
280 module.__dict__.update(values)
281
282 # the module is almost ready... make it visible
283 sys.modules[fqname] = module
284
285 # execute the code within the module's namespace
286 if not is_module:
Tim Peters3d3cfdb2004-08-04 02:29:12 +0000287 try:
Georg Brandl7cae87c2006-09-06 06:51:57 +0000288 exec(code, module.__dict__)
Tim Peters3d3cfdb2004-08-04 02:29:12 +0000289 except:
290 if fqname in sys.modules:
291 del sys.modules[fqname]
292 raise
Greg Steindd6eefb2000-07-18 09:09:48 +0000293
Thomas Hellerbfae1962001-02-12 09:17:06 +0000294 # fetch from sys.modules instead of returning module directly.
Martin v. Löwis70195da2001-07-28 20:33:41 +0000295 # also make module's __name__ agree with fqname, in case
296 # the "exec code in module.__dict__" played games on us.
297 module = sys.modules[fqname]
298 module.__name__ = fqname
299 return module
Greg Steindd6eefb2000-07-18 09:09:48 +0000300
301 def _load_tail(self, m, parts):
302 """Import the rest of the modules, down from the top-level module.
303
304 Returns the last module in the dotted list of modules.
305 """
306 for part in parts:
307 fqname = "%s.%s" % (m.__name__, part)
308 m = self._import_one(m, part, fqname)
309 if not m:
310 raise ImportError, "No module named " + fqname
311 return m
312
313 def _import_fromlist(self, package, fromlist):
314 'Import any sub-modules in the "from" list.'
315
316 # if '*' is present in the fromlist, then look for the '__all__'
317 # variable to find additional items (modules) to import.
318 if '*' in fromlist:
319 fromlist = list(fromlist) + \
320 list(package.__dict__.get('__all__', []))
321
322 for sub in fromlist:
323 # if the name is already present, then don't try to import it (it
324 # might not be a module!).
325 if sub != '*' and not hasattr(package, sub):
326 subname = "%s.%s" % (package.__name__, sub)
327 submod = self._import_one(package, sub, subname)
328 if not submod:
329 raise ImportError, "cannot import name " + subname
330
331 def _do_import(self, parent, parts, fromlist):
332 """Attempt to import the module relative to parent.
333
334 This method is used when the import context specifies that <self>
335 imported the parent module.
336 """
337 top_name = parts[0]
338 top_fqname = parent.__name__ + '.' + top_name
339 top_module = self._import_one(parent, top_name, top_fqname)
340 if not top_module:
341 # this importer and parent could not find the module (relatively)
342 return None
343
344 return self._finish_import(top_module, parts[1:], fromlist)
345
346 ######################################################################
Greg Stein281b8d81999-11-07 12:54:45 +0000347 #
Greg Steindd6eefb2000-07-18 09:09:48 +0000348 # METHODS TO OVERRIDE
349 #
350 def get_code(self, parent, modname, fqname):
351 """Find and retrieve the code for the given module.
Greg Stein281b8d81999-11-07 12:54:45 +0000352
Greg Steindd6eefb2000-07-18 09:09:48 +0000353 parent specifies a parent module to define a context for importing. It
354 may be None, indicating no particular context for the search.
Greg Stein281b8d81999-11-07 12:54:45 +0000355
Greg Steindd6eefb2000-07-18 09:09:48 +0000356 modname specifies a single module (not dotted) within the parent.
Greg Stein281b8d81999-11-07 12:54:45 +0000357
Greg Steindd6eefb2000-07-18 09:09:48 +0000358 fqname specifies the fully-qualified module name. This is a
359 (potentially) dotted name from the "root" of the module namespace
360 down to the modname.
361 If there is no parent, then modname==fqname.
Greg Stein281b8d81999-11-07 12:54:45 +0000362
Greg Steindd6eefb2000-07-18 09:09:48 +0000363 This method should return None, or a 3-tuple.
Greg Stein281b8d81999-11-07 12:54:45 +0000364
Greg Steindd6eefb2000-07-18 09:09:48 +0000365 * If the module was not found, then None should be returned.
Greg Stein281b8d81999-11-07 12:54:45 +0000366
Greg Steindd6eefb2000-07-18 09:09:48 +0000367 * The first item of the 2- or 3-tuple should be the integer 0 or 1,
368 specifying whether the module that was found is a package or not.
Greg Stein281b8d81999-11-07 12:54:45 +0000369
Greg Steindd6eefb2000-07-18 09:09:48 +0000370 * The second item is the code object for the module (it will be
371 executed within the new module's namespace). This item can also
372 be a fully-loaded module object (e.g. loaded from a shared lib).
Greg Steinf23aa1e2000-01-03 02:38:29 +0000373
Greg Steindd6eefb2000-07-18 09:09:48 +0000374 * The third item is a dictionary of name/value pairs that will be
375 inserted into new module before the code object is executed. This
376 is provided in case the module's code expects certain values (such
377 as where the module was found). When the second item is a module
378 object, then these names/values will be inserted *after* the module
379 has been loaded/initialized.
380 """
381 raise RuntimeError, "get_code not implemented"
Greg Stein281b8d81999-11-07 12:54:45 +0000382
383
384######################################################################
385#
Greg Stein63faa011999-11-20 11:22:37 +0000386# Some handy stuff for the Importers
387#
388
Greg Steind4f1d202000-02-18 12:03:40 +0000389# byte-compiled file suffix character
Greg Stein63faa011999-11-20 11:22:37 +0000390_suffix_char = __debug__ and 'c' or 'o'
391
392# byte-compiled file suffix
393_suffix = '.py' + _suffix_char
394
Greg Stein63faa011999-11-20 11:22:37 +0000395def _compile(pathname, timestamp):
Greg Steindd6eefb2000-07-18 09:09:48 +0000396 """Compile (and cache) a Python source file.
Greg Stein63faa011999-11-20 11:22:37 +0000397
Greg Steindd6eefb2000-07-18 09:09:48 +0000398 The file specified by <pathname> is compiled to a code object and
399 returned.
Greg Stein63faa011999-11-20 11:22:37 +0000400
Greg Steindd6eefb2000-07-18 09:09:48 +0000401 Presuming the appropriate privileges exist, the bytecodes will be
402 saved back to the filesystem for future imports. The source file's
403 modification timestamp must be provided as a Long value.
404 """
Jeremy Hylton13f99d72002-06-28 23:32:51 +0000405 codestring = open(pathname, 'rU').read()
Greg Steindd6eefb2000-07-18 09:09:48 +0000406 if codestring and codestring[-1] != '\n':
407 codestring = codestring + '\n'
408 code = __builtin__.compile(codestring, pathname, 'exec')
Greg Stein63faa011999-11-20 11:22:37 +0000409
Greg Steindd6eefb2000-07-18 09:09:48 +0000410 # try to cache the compiled code
411 try:
412 f = open(pathname + _suffix_char, 'wb')
413 except IOError:
414 pass
415 else:
416 f.write('\0\0\0\0')
417 f.write(struct.pack('<I', timestamp))
418 marshal.dump(code, f)
419 f.flush()
420 f.seek(0, 0)
421 f.write(imp.get_magic())
422 f.close()
Greg Stein63faa011999-11-20 11:22:37 +0000423
Greg Steindd6eefb2000-07-18 09:09:48 +0000424 return code
Greg Stein63faa011999-11-20 11:22:37 +0000425
426_os_stat = _os_path_join = None
427def _os_bootstrap():
Greg Steindd6eefb2000-07-18 09:09:48 +0000428 "Set up 'os' module replacement functions for use during import bootstrap."
Greg Stein63faa011999-11-20 11:22:37 +0000429
Greg Steindd6eefb2000-07-18 09:09:48 +0000430 names = sys.builtin_module_names
Greg Stein63faa011999-11-20 11:22:37 +0000431
Greg Steindd6eefb2000-07-18 09:09:48 +0000432 join = None
433 if 'posix' in names:
434 sep = '/'
435 from posix import stat
436 elif 'nt' in names:
437 sep = '\\'
438 from nt import stat
439 elif 'dos' in names:
440 sep = '\\'
441 from dos import stat
442 elif 'os2' in names:
443 sep = '\\'
444 from os2 import stat
445 elif 'mac' in names:
446 from mac import stat
447 def join(a, b):
448 if a == '':
449 return b
Greg Steindd6eefb2000-07-18 09:09:48 +0000450 if ':' not in a:
451 a = ':' + a
Fred Drake8152d322000-12-12 23:20:45 +0000452 if a[-1:] != ':':
Greg Steindd6eefb2000-07-18 09:09:48 +0000453 a = a + ':'
454 return a + b
455 else:
456 raise ImportError, 'no os specific module found'
Greg Stein63faa011999-11-20 11:22:37 +0000457
Greg Steindd6eefb2000-07-18 09:09:48 +0000458 if join is None:
459 def join(a, b, sep=sep):
460 if a == '':
461 return b
462 lastchar = a[-1:]
463 if lastchar == '/' or lastchar == sep:
464 return a + b
465 return a + sep + b
Greg Stein63faa011999-11-20 11:22:37 +0000466
Greg Steindd6eefb2000-07-18 09:09:48 +0000467 global _os_stat
468 _os_stat = stat
469
470 global _os_path_join
471 _os_path_join = join
Greg Stein63faa011999-11-20 11:22:37 +0000472
473def _os_path_isdir(pathname):
Greg Steindd6eefb2000-07-18 09:09:48 +0000474 "Local replacement for os.path.isdir()."
475 try:
476 s = _os_stat(pathname)
477 except OSError:
478 return None
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000479 return (s.st_mode & 0o170000) == 0o040000
Greg Stein63faa011999-11-20 11:22:37 +0000480
481def _timestamp(pathname):
Greg Steindd6eefb2000-07-18 09:09:48 +0000482 "Return the file modification time as a Long."
483 try:
484 s = _os_stat(pathname)
485 except OSError:
486 return None
Guido van Rossume2a383d2007-01-15 16:59:06 +0000487 return int(s.st_mtime)
Greg Stein63faa011999-11-20 11:22:37 +0000488
Greg Stein63faa011999-11-20 11:22:37 +0000489
490######################################################################
491#
492# Emulate the import mechanism for builtin and frozen modules
493#
494class BuiltinImporter(Importer):
Greg Steindd6eefb2000-07-18 09:09:48 +0000495 def get_code(self, parent, modname, fqname):
496 if parent:
497 # these modules definitely do not occur within a package context
498 return None
Greg Stein63faa011999-11-20 11:22:37 +0000499
Greg Steindd6eefb2000-07-18 09:09:48 +0000500 # look for the module
501 if imp.is_builtin(modname):
502 type = imp.C_BUILTIN
503 elif imp.is_frozen(modname):
504 type = imp.PY_FROZEN
505 else:
506 # not found
507 return None
Greg Stein63faa011999-11-20 11:22:37 +0000508
Greg Steindd6eefb2000-07-18 09:09:48 +0000509 # got it. now load and return it.
510 module = imp.load_module(modname, None, modname, ('', '', type))
511 return 0, module, { }
Greg Stein63faa011999-11-20 11:22:37 +0000512
513
514######################################################################
Greg Steinf23aa1e2000-01-03 02:38:29 +0000515#
516# Internal importer used for importing from the filesystem
517#
518class _FilesystemImporter(Importer):
Greg Steindd6eefb2000-07-18 09:09:48 +0000519 def __init__(self):
520 self.suffixes = [ ]
Greg Stein3bb578c2000-02-18 13:04:10 +0000521
Greg Steindd6eefb2000-07-18 09:09:48 +0000522 def add_suffix(self, suffix, importFunc):
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000523 assert hasattr(importFunc, '__call__')
Greg Steindd6eefb2000-07-18 09:09:48 +0000524 self.suffixes.append((suffix, importFunc))
Greg Steinf23aa1e2000-01-03 02:38:29 +0000525
Greg Steindd6eefb2000-07-18 09:09:48 +0000526 def import_from_dir(self, dir, fqname):
527 result = self._import_pathname(_os_path_join(dir, fqname), fqname)
528 if result:
529 return self._process_result(result, fqname)
530 return None
Greg Steinf23aa1e2000-01-03 02:38:29 +0000531
Greg Steindd6eefb2000-07-18 09:09:48 +0000532 def get_code(self, parent, modname, fqname):
533 # This importer is never used with an empty parent. Its existence is
534 # private to the ImportManager. The ImportManager uses the
535 # import_from_dir() method to import top-level modules/packages.
536 # This method is only used when we look for a module within a package.
537 assert parent
Greg Steinf23aa1e2000-01-03 02:38:29 +0000538
Thomas Wouterscf297e42007-02-23 15:07:44 +0000539 for submodule_path in parent.__path__:
540 code = self._import_pathname(_os_path_join(submodule_path, modname), fqname)
541 if code is not None:
542 return code
Greg Steindd6eefb2000-07-18 09:09:48 +0000543 return self._import_pathname(_os_path_join(parent.__pkgdir__, modname),
Greg Steinf23aa1e2000-01-03 02:38:29 +0000544 fqname)
Greg Steinf23aa1e2000-01-03 02:38:29 +0000545
Greg Steindd6eefb2000-07-18 09:09:48 +0000546 def _import_pathname(self, pathname, fqname):
547 if _os_path_isdir(pathname):
548 result = self._import_pathname(_os_path_join(pathname, '__init__'),
549 fqname)
550 if result:
551 values = result[2]
552 values['__pkgdir__'] = pathname
553 values['__path__'] = [ pathname ]
554 return 1, result[1], values
555 return None
556
557 for suffix, importFunc in self.suffixes:
558 filename = pathname + suffix
559 try:
560 finfo = _os_stat(filename)
561 except OSError:
562 pass
563 else:
564 return importFunc(filename, finfo, fqname)
565 return None
Greg Steinf23aa1e2000-01-03 02:38:29 +0000566
567######################################################################
568#
569# SUFFIX-BASED IMPORTERS
570#
571
Greg Stein3bb578c2000-02-18 13:04:10 +0000572def py_suffix_importer(filename, finfo, fqname):
Greg Steindd6eefb2000-07-18 09:09:48 +0000573 file = filename[:-3] + _suffix
Guido van Rossume2a383d2007-01-15 16:59:06 +0000574 t_py = int(finfo[8])
Greg Steindd6eefb2000-07-18 09:09:48 +0000575 t_pyc = _timestamp(file)
Greg Steinf23aa1e2000-01-03 02:38:29 +0000576
Greg Steindd6eefb2000-07-18 09:09:48 +0000577 code = None
578 if t_pyc is not None and t_pyc >= t_py:
579 f = open(file, 'rb')
580 if f.read(4) == imp.get_magic():
581 t = struct.unpack('<I', f.read(4))[0]
582 if t == t_py:
583 code = marshal.load(f)
584 f.close()
585 if code is None:
586 file = filename
587 code = _compile(file, t_py)
Greg Steinf23aa1e2000-01-03 02:38:29 +0000588
Greg Steindd6eefb2000-07-18 09:09:48 +0000589 return 0, code, { '__file__' : file }
Greg Steinf23aa1e2000-01-03 02:38:29 +0000590
Greg Stein3bb578c2000-02-18 13:04:10 +0000591class DynLoadSuffixImporter:
Greg Steindd6eefb2000-07-18 09:09:48 +0000592 def __init__(self, desc):
593 self.desc = desc
Greg Steinf23aa1e2000-01-03 02:38:29 +0000594
Greg Steindd6eefb2000-07-18 09:09:48 +0000595 def import_file(self, filename, finfo, fqname):
596 fp = open(filename, self.desc[1])
597 module = imp.load_module(fqname, fp, filename, self.desc)
598 module.__file__ = filename
599 return 0, module, { }
Greg Steinf23aa1e2000-01-03 02:38:29 +0000600
601
602######################################################################
Greg Stein63faa011999-11-20 11:22:37 +0000603
Greg Stein63faa011999-11-20 11:22:37 +0000604def _print_importers():
Greg Steindd6eefb2000-07-18 09:09:48 +0000605 items = sys.modules.items()
606 items.sort()
607 for name, module in items:
608 if module:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000609 print(name, module.__dict__.get('__importer__', '-- no importer'))
Greg Steindd6eefb2000-07-18 09:09:48 +0000610 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000611 print(name, '-- non-existent module')
Greg Stein63faa011999-11-20 11:22:37 +0000612
Greg Steinf23aa1e2000-01-03 02:38:29 +0000613def _test_revamp():
Greg Steindd6eefb2000-07-18 09:09:48 +0000614 ImportManager().install()
615 sys.path.insert(0, BuiltinImporter())
Greg Steinf23aa1e2000-01-03 02:38:29 +0000616
Greg Stein281b8d81999-11-07 12:54:45 +0000617######################################################################
Greg Stein42b9bc72000-02-19 13:36:23 +0000618
619#
620# TODO
621#
622# from Finn Bock:
Greg Stein42b9bc72000-02-19 13:36:23 +0000623# type(sys) is not a module in JPython. what to use instead?
624# imp.C_EXTENSION is not in JPython. same for get_suffixes and new_module
625#
626# given foo.py of:
627# import sys
628# sys.modules['foo'] = sys
629#
630# ---- standard import mechanism
631# >>> import foo
632# >>> foo
633# <module 'sys' (built-in)>
634#
635# ---- revamped import mechanism
636# >>> import imputil
637# >>> imputil._test_revamp()
638# >>> import foo
639# >>> foo
640# <module 'foo' from 'foo.py'>
641#
642#
643# from MAL:
644# should BuiltinImporter exist in sys.path or hard-wired in ImportManager?
645# need __path__ processing
646# performance
647# move chaining to a subclass [gjs: it's been nuked]
Greg Stein42b9bc72000-02-19 13:36:23 +0000648# deinstall should be possible
649# query mechanism needed: is a specific Importer installed?
650# py/pyc/pyo piping hooks to filter/process these files
651# wish list:
652# distutils importer hooked to list of standard Internet repositories
653# module->file location mapper to speed FS-based imports
654# relative imports
655# keep chaining so that it can play nice with other import hooks
656#
657# from Gordon:
658# push MAL's mapper into sys.path[0] as a cache (hard-coded for apps)
659#
660# from Guido:
Greg Stein42b9bc72000-02-19 13:36:23 +0000661# need hook for MAL's walk-me-up import strategy, or Tim's absolute strategy
Fred Drake8152d322000-12-12 23:20:45 +0000662# watch out for sys.modules[...] is None
Greg Stein42b9bc72000-02-19 13:36:23 +0000663# flag to force absolute imports? (speeds _determine_import_context and
664# checking for a relative module)
665# insert names of archives into sys.path (see quote below)
Greg Stein42b9bc72000-02-19 13:36:23 +0000666# shift import mechanisms and policies around; provide for hooks, overrides
667# (see quote below)
668# add get_source stuff
669# get_topcode and get_subcode
670# CRLF handling in _compile
671# race condition in _compile
672# refactoring of os.py to deal with _os_bootstrap problem
673# any special handling to do for importing a module with a SyntaxError?
674# (e.g. clean up the traceback)
675# implement "domain" for path-type functionality using pkg namespace
676# (rather than FS-names like __path__)
677# don't use the word "private"... maybe "internal"
678#
679#
680# Guido's comments on sys.path caching:
Tim Peters07e99cb2001-01-14 23:47:14 +0000681#
Greg Stein42b9bc72000-02-19 13:36:23 +0000682# We could cache this in a dictionary: the ImportManager can have a
683# cache dict mapping pathnames to importer objects, and a separate
684# method for coming up with an importer given a pathname that's not yet
685# in the cache. The method should do a stat and/or look at the
686# extension to decide which importer class to use; you can register new
687# importer classes by registering a suffix or a Boolean function, plus a
688# class. If you register a new importer class, the cache is zapped.
689# The cache is independent from sys.path (but maintained per
690# ImportManager instance) so that rearrangements of sys.path do the
691# right thing. If a path is dropped from sys.path the corresponding
692# cache entry is simply no longer used.
693#
694# My/Guido's comments on factoring ImportManager and Importer:
695#
696# > However, we still have a tension occurring here:
Tim Peters07e99cb2001-01-14 23:47:14 +0000697# >
Greg Stein42b9bc72000-02-19 13:36:23 +0000698# > 1) implementing policy in ImportManager assists in single-point policy
Guido van Rossuma8add0e2007-05-14 22:03:55 +0000699# > changes for app situations
Greg Stein42b9bc72000-02-19 13:36:23 +0000700# > 2) implementing policy in Importer assists in package-private policy
701# > changes for normal, operating conditions
Tim Peters07e99cb2001-01-14 23:47:14 +0000702# >
Greg Stein42b9bc72000-02-19 13:36:23 +0000703# > I'll see if I can sort out a way to do this. Maybe the Importer class will
704# > implement the methods (which can be overridden to change policy) by
705# > delegating to ImportManager.
Tim Peters07e99cb2001-01-14 23:47:14 +0000706#
Greg Stein42b9bc72000-02-19 13:36:23 +0000707# Maybe also think about what kind of policies an Importer would be
708# likely to want to change. I have a feeling that a lot of the code
709# there is actually not so much policy but a *necessity* to get things
710# working given the calling conventions for the __import__ hook: whether
711# to return the head or tail of a dotted name, or when to do the "finish
712# fromlist" stuff.
713#