blob: 6017f6cb230fa73d25ac7f428d8e460a3fb5be0c [file] [log] [blame]
Greg Stein281b8d81999-11-07 12:54:45 +00001#
Greg Stein99a56212000-06-26 17:31:49 +00002# imputil.py: import utilities
Greg Stein281b8d81999-11-07 12:54:45 +00003#
Greg Stein99a56212000-06-26 17:31:49 +00004
5### docco needed here and in Docs/ ...
Greg Stein281b8d81999-11-07 12:54:45 +00006
Greg Stein281b8d81999-11-07 12:54:45 +00007# note: avoid importing non-builtin modules
Tim Peters07e99cb2001-01-14 23:47:14 +00008import imp ### not available in JPython?
Greg Stein281b8d81999-11-07 12:54:45 +00009import sys
Greg Stein7ec28d21999-11-20 12:31:07 +000010import __builtin__
Greg Stein281b8d81999-11-07 12:54:45 +000011
12# for the DirectoryImporter
13import struct
14import marshal
15
Skip Montanaro17ab1232001-01-24 06:27:27 +000016__all__ = ["ImportManager","Importer","BuiltinImporter"]
17
Greg Steinf23aa1e2000-01-03 02:38:29 +000018_StringType = type('')
Tim Peters07e99cb2001-01-14 23:47:14 +000019_ModuleType = type(sys) ### doesn't work in JPython...
Greg Steinf23aa1e2000-01-03 02:38:29 +000020
21class ImportManager:
Greg Steindd6eefb2000-07-18 09:09:48 +000022 "Manage the import process."
Greg Stein281b8d81999-11-07 12:54:45 +000023
Greg Steindd6eefb2000-07-18 09:09:48 +000024 def install(self, namespace=vars(__builtin__)):
25 "Install this ImportManager into the specified namespace."
Greg Steind4f1d202000-02-18 12:03:40 +000026
Greg Steindd6eefb2000-07-18 09:09:48 +000027 if isinstance(namespace, _ModuleType):
28 namespace = vars(namespace)
Greg Steind4f1d202000-02-18 12:03:40 +000029
Greg Stein76977bb2001-04-07 16:05:24 +000030 # Note: we have no notion of "chaining"
Greg Stein3bb578c2000-02-18 13:04:10 +000031
Greg Stein76977bb2001-04-07 16:05:24 +000032 # Record the previous import hook, then install our own.
33 self.previous_importer = namespace['__import__']
34 self.namespace = namespace
Greg Steindd6eefb2000-07-18 09:09:48 +000035 namespace['__import__'] = self._import_hook
Greg Stein76977bb2001-04-07 16:05:24 +000036
Greg Steindd6eefb2000-07-18 09:09:48 +000037 ### fix this
38 #namespace['reload'] = self._reload_hook
Greg Steinf23aa1e2000-01-03 02:38:29 +000039
Greg Stein76977bb2001-04-07 16:05:24 +000040 def uninstall(self):
41 "Restore the previous import mechanism."
42 self.namespace['__import__'] = self.previous_importer
43
Greg Steindd6eefb2000-07-18 09:09:48 +000044 def add_suffix(self, suffix, importFunc):
45 assert callable(importFunc)
46 self.fs_imp.add_suffix(suffix, importFunc)
Greg Stein281b8d81999-11-07 12:54:45 +000047
Greg Steindd6eefb2000-07-18 09:09:48 +000048 ######################################################################
49 #
50 # PRIVATE METHODS
51 #
Greg Stein3bb578c2000-02-18 13:04:10 +000052
Greg Steindd6eefb2000-07-18 09:09:48 +000053 clsFilesystemImporter = None
Greg Stein281b8d81999-11-07 12:54:45 +000054
Greg Steindd6eefb2000-07-18 09:09:48 +000055 def __init__(self, fs_imp=None):
56 # we're definitely going to be importing something in the future,
57 # so let's just load the OS-related facilities.
58 if not _os_stat:
59 _os_bootstrap()
Greg Stein3bb578c2000-02-18 13:04:10 +000060
Greg Steindd6eefb2000-07-18 09:09:48 +000061 # This is the Importer that we use for grabbing stuff from the
62 # filesystem. It defines one more method (import_from_dir) for our use.
63 if not fs_imp:
64 cls = self.clsFilesystemImporter or _FilesystemImporter
65 fs_imp = cls()
66 self.fs_imp = fs_imp
Greg Stein281b8d81999-11-07 12:54:45 +000067
Greg Steindd6eefb2000-07-18 09:09:48 +000068 # Initialize the set of suffixes that we recognize and import.
69 # The default will import dynamic-load modules first, followed by
70 # .py files (or a .py file's cached bytecode)
71 for desc in imp.get_suffixes():
72 if desc[2] == imp.C_EXTENSION:
73 self.add_suffix(desc[0],
74 DynLoadSuffixImporter(desc).import_file)
75 self.add_suffix('.py', py_suffix_importer)
Greg Steinf23aa1e2000-01-03 02:38:29 +000076
Greg Steindd6eefb2000-07-18 09:09:48 +000077 def _import_hook(self, fqname, globals=None, locals=None, fromlist=None):
78 """Python calls this hook to locate and import a module."""
Greg Stein63faa011999-11-20 11:22:37 +000079
Martin v. Löwisd3011cd2001-07-28 17:59:34 +000080 parts = fqname.split('.')
Greg Stein281b8d81999-11-07 12:54:45 +000081
Greg Steindd6eefb2000-07-18 09:09:48 +000082 # determine the context of this import
83 parent = self._determine_import_context(globals)
Greg Stein281b8d81999-11-07 12:54:45 +000084
Greg Steindd6eefb2000-07-18 09:09:48 +000085 # if there is a parent, then its importer should manage this import
86 if parent:
87 module = parent.__importer__._do_import(parent, parts, fromlist)
88 if module:
89 return module
Greg Stein281b8d81999-11-07 12:54:45 +000090
Greg Steindd6eefb2000-07-18 09:09:48 +000091 # has the top module already been imported?
92 try:
93 top_module = sys.modules[parts[0]]
94 except KeyError:
95
96 # look for the topmost module
97 top_module = self._import_top_module(parts[0])
98 if not top_module:
99 # the topmost module wasn't found at all.
100 raise ImportError, 'No module named ' + fqname
101
102 # fast-path simple imports
103 if len(parts) == 1:
104 if not fromlist:
105 return top_module
106
107 if not top_module.__dict__.get('__ispkg__'):
108 # __ispkg__ isn't defined (the module was not imported by us),
109 # or it is zero.
110 #
111 # In the former case, there is no way that we could import
112 # sub-modules that occur in the fromlist (but we can't raise an
113 # error because it may just be names) because we don't know how
114 # to deal with packages that were imported by other systems.
115 #
116 # In the latter case (__ispkg__ == 0), there can't be any sub-
117 # modules present, so we can just return.
118 #
119 # In both cases, since len(parts) == 1, the top_module is also
120 # the "bottom" which is the defined return when a fromlist
121 # exists.
122 return top_module
123
124 importer = top_module.__dict__.get('__importer__')
125 if importer:
126 return importer._finish_import(top_module, parts[1:], fromlist)
127
128 # If the importer does not exist, then we have to bail. A missing
129 # importer means that something else imported the module, and we have
130 # no knowledge of how to get sub-modules out of the thing.
Greg Steinf23aa1e2000-01-03 02:38:29 +0000131 raise ImportError, 'No module named ' + fqname
Greg Steinf23aa1e2000-01-03 02:38:29 +0000132
Greg Steindd6eefb2000-07-18 09:09:48 +0000133 def _determine_import_context(self, globals):
134 """Returns the context in which a module should be imported.
Greg Steinf23aa1e2000-01-03 02:38:29 +0000135
Greg Steindd6eefb2000-07-18 09:09:48 +0000136 The context could be a loaded (package) module and the imported module
137 will be looked for within that package. The context could also be None,
138 meaning there is no context -- the module should be looked for as a
139 "top-level" module.
140 """
Greg Steinf23aa1e2000-01-03 02:38:29 +0000141
Greg Steindd6eefb2000-07-18 09:09:48 +0000142 if not globals or not globals.get('__importer__'):
143 # globals does not refer to one of our modules or packages. That
144 # implies there is no relative import context (as far as we are
145 # concerned), and it should just pick it off the standard path.
146 return None
Greg Steinf23aa1e2000-01-03 02:38:29 +0000147
Greg Steindd6eefb2000-07-18 09:09:48 +0000148 # The globals refer to a module or package of ours. It will define
149 # the context of the new import. Get the module/package fqname.
150 parent_fqname = globals['__name__']
Greg Steinf23aa1e2000-01-03 02:38:29 +0000151
Greg Steindd6eefb2000-07-18 09:09:48 +0000152 # if a package is performing the import, then return itself (imports
153 # refer to pkg contents)
154 if globals['__ispkg__']:
155 parent = sys.modules[parent_fqname]
156 assert globals is parent.__dict__
157 return parent
Greg Steinf23aa1e2000-01-03 02:38:29 +0000158
Martin v. Löwisd3011cd2001-07-28 17:59:34 +0000159 i = parent_fqname.rfind('.')
Greg Steinf23aa1e2000-01-03 02:38:29 +0000160
Greg Steindd6eefb2000-07-18 09:09:48 +0000161 # a module outside of a package has no particular import context
162 if i == -1:
163 return None
Greg Steinf23aa1e2000-01-03 02:38:29 +0000164
Greg Steindd6eefb2000-07-18 09:09:48 +0000165 # if a module in a package is performing the import, then return the
166 # package (imports refer to siblings)
167 parent_fqname = parent_fqname[:i]
168 parent = sys.modules[parent_fqname]
169 assert parent.__name__ == parent_fqname
170 return parent
Greg Steinf23aa1e2000-01-03 02:38:29 +0000171
Greg Steindd6eefb2000-07-18 09:09:48 +0000172 def _import_top_module(self, name):
173 # scan sys.path looking for a location in the filesystem that contains
174 # the module, or an Importer object that can import the module.
175 for item in sys.path:
176 if isinstance(item, _StringType):
177 module = self.fs_imp.import_from_dir(item, name)
178 else:
179 module = item.import_top(name)
180 if module:
181 return module
182 return None
Greg Steinf23aa1e2000-01-03 02:38:29 +0000183
Greg Steindd6eefb2000-07-18 09:09:48 +0000184 def _reload_hook(self, module):
185 "Python calls this hook to reload a module."
Greg Steinf23aa1e2000-01-03 02:38:29 +0000186
Greg Steindd6eefb2000-07-18 09:09:48 +0000187 # reloading of a module may or may not be possible (depending on the
188 # importer), but at least we can validate that it's ours to reload
189 importer = module.__dict__.get('__importer__')
190 if not importer:
191 ### oops. now what...
192 pass
Greg Steinf23aa1e2000-01-03 02:38:29 +0000193
Greg Steindd6eefb2000-07-18 09:09:48 +0000194 # okay. it is using the imputil system, and we must delegate it, but
195 # we don't know what to do (yet)
196 ### we should blast the module dict and do another get_code(). need to
197 ### flesh this out and add proper docco...
198 raise SystemError, "reload not yet implemented"
Greg Steinf23aa1e2000-01-03 02:38:29 +0000199
200
201class Importer:
Greg Steindd6eefb2000-07-18 09:09:48 +0000202 "Base class for replacing standard import functions."
Greg Steinf23aa1e2000-01-03 02:38:29 +0000203
Greg Steindd6eefb2000-07-18 09:09:48 +0000204 def import_top(self, name):
205 "Import a top-level module."
206 return self._import_one(None, name, name)
Greg Steinf23aa1e2000-01-03 02:38:29 +0000207
Greg Steindd6eefb2000-07-18 09:09:48 +0000208 ######################################################################
Greg Stein281b8d81999-11-07 12:54:45 +0000209 #
Greg Steindd6eefb2000-07-18 09:09:48 +0000210 # PRIVATE METHODS
Greg Stein281b8d81999-11-07 12:54:45 +0000211 #
Greg Steindd6eefb2000-07-18 09:09:48 +0000212 def _finish_import(self, top, parts, fromlist):
213 # if "a.b.c" was provided, then load the ".b.c" portion down from
214 # below the top-level module.
215 bottom = self._load_tail(top, parts)
Greg Stein281b8d81999-11-07 12:54:45 +0000216
Greg Steindd6eefb2000-07-18 09:09:48 +0000217 # if the form is "import a.b.c", then return "a"
218 if not fromlist:
219 # no fromlist: return the top of the import tree
220 return top
221
222 # the top module was imported by self.
223 #
224 # this means that the bottom module was also imported by self (just
225 # now, or in the past and we fetched it from sys.modules).
226 #
227 # since we imported/handled the bottom module, this means that we can
228 # also handle its fromlist (and reliably use __ispkg__).
229
230 # if the bottom node is a package, then (potentially) import some
231 # modules.
232 #
233 # note: if it is not a package, then "fromlist" refers to names in
234 # the bottom module rather than modules.
235 # note: for a mix of names and modules in the fromlist, we will
236 # import all modules and insert those into the namespace of
237 # the package module. Python will pick up all fromlist names
238 # from the bottom (package) module; some will be modules that
239 # we imported and stored in the namespace, others are expected
240 # to be present already.
241 if bottom.__ispkg__:
242 self._import_fromlist(bottom, fromlist)
243
244 # if the form is "from a.b import c, d" then return "b"
245 return bottom
246
247 def _import_one(self, parent, modname, fqname):
248 "Import a single module."
249
250 # has the module already been imported?
251 try:
252 return sys.modules[fqname]
253 except KeyError:
254 pass
255
256 # load the module's code, or fetch the module itself
257 result = self.get_code(parent, modname, fqname)
258 if result is None:
259 return None
260
261 module = self._process_result(result, fqname)
262
263 # insert the module into its parent
264 if parent:
265 setattr(parent, modname, module)
266 return module
267
268 def _process_result(self, (ispkg, code, values), fqname):
269 # did get_code() return an actual module? (rather than a code object)
270 is_module = isinstance(code, _ModuleType)
271
272 # use the returned module, or create a new one to exec code into
273 if is_module:
274 module = code
275 else:
276 module = imp.new_module(fqname)
277
278 ### record packages a bit differently??
279 module.__importer__ = self
280 module.__ispkg__ = ispkg
281
282 # insert additional values into the module (before executing the code)
283 module.__dict__.update(values)
284
285 # the module is almost ready... make it visible
286 sys.modules[fqname] = module
287
288 # execute the code within the module's namespace
289 if not is_module:
290 exec code in module.__dict__
291
Thomas Hellerbfae1962001-02-12 09:17:06 +0000292 # fetch from sys.modules instead of returning module directly.
293 return sys.modules[fqname]
Greg Steindd6eefb2000-07-18 09:09:48 +0000294
295 def _load_tail(self, m, parts):
296 """Import the rest of the modules, down from the top-level module.
297
298 Returns the last module in the dotted list of modules.
299 """
300 for part in parts:
301 fqname = "%s.%s" % (m.__name__, part)
302 m = self._import_one(m, part, fqname)
303 if not m:
304 raise ImportError, "No module named " + fqname
305 return m
306
307 def _import_fromlist(self, package, fromlist):
308 'Import any sub-modules in the "from" list.'
309
310 # if '*' is present in the fromlist, then look for the '__all__'
311 # variable to find additional items (modules) to import.
312 if '*' in fromlist:
313 fromlist = list(fromlist) + \
314 list(package.__dict__.get('__all__', []))
315
316 for sub in fromlist:
317 # if the name is already present, then don't try to import it (it
318 # might not be a module!).
319 if sub != '*' and not hasattr(package, sub):
320 subname = "%s.%s" % (package.__name__, sub)
321 submod = self._import_one(package, sub, subname)
322 if not submod:
323 raise ImportError, "cannot import name " + subname
324
325 def _do_import(self, parent, parts, fromlist):
326 """Attempt to import the module relative to parent.
327
328 This method is used when the import context specifies that <self>
329 imported the parent module.
330 """
331 top_name = parts[0]
332 top_fqname = parent.__name__ + '.' + top_name
333 top_module = self._import_one(parent, top_name, top_fqname)
334 if not top_module:
335 # this importer and parent could not find the module (relatively)
336 return None
337
338 return self._finish_import(top_module, parts[1:], fromlist)
339
340 ######################################################################
Greg Stein281b8d81999-11-07 12:54:45 +0000341 #
Greg Steindd6eefb2000-07-18 09:09:48 +0000342 # METHODS TO OVERRIDE
343 #
344 def get_code(self, parent, modname, fqname):
345 """Find and retrieve the code for the given module.
Greg Stein281b8d81999-11-07 12:54:45 +0000346
Greg Steindd6eefb2000-07-18 09:09:48 +0000347 parent specifies a parent module to define a context for importing. It
348 may be None, indicating no particular context for the search.
Greg Stein281b8d81999-11-07 12:54:45 +0000349
Greg Steindd6eefb2000-07-18 09:09:48 +0000350 modname specifies a single module (not dotted) within the parent.
Greg Stein281b8d81999-11-07 12:54:45 +0000351
Greg Steindd6eefb2000-07-18 09:09:48 +0000352 fqname specifies the fully-qualified module name. This is a
353 (potentially) dotted name from the "root" of the module namespace
354 down to the modname.
355 If there is no parent, then modname==fqname.
Greg Stein281b8d81999-11-07 12:54:45 +0000356
Greg Steindd6eefb2000-07-18 09:09:48 +0000357 This method should return None, or a 3-tuple.
Greg Stein281b8d81999-11-07 12:54:45 +0000358
Greg Steindd6eefb2000-07-18 09:09:48 +0000359 * If the module was not found, then None should be returned.
Greg Stein281b8d81999-11-07 12:54:45 +0000360
Greg Steindd6eefb2000-07-18 09:09:48 +0000361 * The first item of the 2- or 3-tuple should be the integer 0 or 1,
362 specifying whether the module that was found is a package or not.
Greg Stein281b8d81999-11-07 12:54:45 +0000363
Greg Steindd6eefb2000-07-18 09:09:48 +0000364 * The second item is the code object for the module (it will be
365 executed within the new module's namespace). This item can also
366 be a fully-loaded module object (e.g. loaded from a shared lib).
Greg Steinf23aa1e2000-01-03 02:38:29 +0000367
Greg Steindd6eefb2000-07-18 09:09:48 +0000368 * The third item is a dictionary of name/value pairs that will be
369 inserted into new module before the code object is executed. This
370 is provided in case the module's code expects certain values (such
371 as where the module was found). When the second item is a module
372 object, then these names/values will be inserted *after* the module
373 has been loaded/initialized.
374 """
375 raise RuntimeError, "get_code not implemented"
Greg Stein281b8d81999-11-07 12:54:45 +0000376
377
378######################################################################
379#
Greg Stein63faa011999-11-20 11:22:37 +0000380# Some handy stuff for the Importers
381#
382
Greg Steind4f1d202000-02-18 12:03:40 +0000383# byte-compiled file suffix character
Greg Stein63faa011999-11-20 11:22:37 +0000384_suffix_char = __debug__ and 'c' or 'o'
385
386# byte-compiled file suffix
387_suffix = '.py' + _suffix_char
388
Greg Stein63faa011999-11-20 11:22:37 +0000389def _compile(pathname, timestamp):
Greg Steindd6eefb2000-07-18 09:09:48 +0000390 """Compile (and cache) a Python source file.
Greg Stein63faa011999-11-20 11:22:37 +0000391
Greg Steindd6eefb2000-07-18 09:09:48 +0000392 The file specified by <pathname> is compiled to a code object and
393 returned.
Greg Stein63faa011999-11-20 11:22:37 +0000394
Greg Steindd6eefb2000-07-18 09:09:48 +0000395 Presuming the appropriate privileges exist, the bytecodes will be
396 saved back to the filesystem for future imports. The source file's
397 modification timestamp must be provided as a Long value.
398 """
399 codestring = open(pathname, 'r').read()
400 if codestring and codestring[-1] != '\n':
401 codestring = codestring + '\n'
402 code = __builtin__.compile(codestring, pathname, 'exec')
Greg Stein63faa011999-11-20 11:22:37 +0000403
Greg Steindd6eefb2000-07-18 09:09:48 +0000404 # try to cache the compiled code
405 try:
406 f = open(pathname + _suffix_char, 'wb')
407 except IOError:
408 pass
409 else:
410 f.write('\0\0\0\0')
411 f.write(struct.pack('<I', timestamp))
412 marshal.dump(code, f)
413 f.flush()
414 f.seek(0, 0)
415 f.write(imp.get_magic())
416 f.close()
Greg Stein63faa011999-11-20 11:22:37 +0000417
Greg Steindd6eefb2000-07-18 09:09:48 +0000418 return code
Greg Stein63faa011999-11-20 11:22:37 +0000419
420_os_stat = _os_path_join = None
421def _os_bootstrap():
Greg Steindd6eefb2000-07-18 09:09:48 +0000422 "Set up 'os' module replacement functions for use during import bootstrap."
Greg Stein63faa011999-11-20 11:22:37 +0000423
Greg Steindd6eefb2000-07-18 09:09:48 +0000424 names = sys.builtin_module_names
Greg Stein63faa011999-11-20 11:22:37 +0000425
Greg Steindd6eefb2000-07-18 09:09:48 +0000426 join = None
427 if 'posix' in names:
428 sep = '/'
429 from posix import stat
430 elif 'nt' in names:
431 sep = '\\'
432 from nt import stat
433 elif 'dos' in names:
434 sep = '\\'
435 from dos import stat
436 elif 'os2' in names:
437 sep = '\\'
438 from os2 import stat
439 elif 'mac' in names:
440 from mac import stat
441 def join(a, b):
442 if a == '':
443 return b
444 path = s
445 if ':' not in a:
446 a = ':' + a
Fred Drake8152d322000-12-12 23:20:45 +0000447 if a[-1:] != ':':
Greg Steindd6eefb2000-07-18 09:09:48 +0000448 a = a + ':'
449 return a + b
450 else:
451 raise ImportError, 'no os specific module found'
Greg Stein63faa011999-11-20 11:22:37 +0000452
Greg Steindd6eefb2000-07-18 09:09:48 +0000453 if join is None:
454 def join(a, b, sep=sep):
455 if a == '':
456 return b
457 lastchar = a[-1:]
458 if lastchar == '/' or lastchar == sep:
459 return a + b
460 return a + sep + b
Greg Stein63faa011999-11-20 11:22:37 +0000461
Greg Steindd6eefb2000-07-18 09:09:48 +0000462 global _os_stat
463 _os_stat = stat
464
465 global _os_path_join
466 _os_path_join = join
Greg Stein63faa011999-11-20 11:22:37 +0000467
468def _os_path_isdir(pathname):
Greg Steindd6eefb2000-07-18 09:09:48 +0000469 "Local replacement for os.path.isdir()."
470 try:
471 s = _os_stat(pathname)
472 except OSError:
473 return None
474 return (s[0] & 0170000) == 0040000
Greg Stein63faa011999-11-20 11:22:37 +0000475
476def _timestamp(pathname):
Greg Steindd6eefb2000-07-18 09:09:48 +0000477 "Return the file modification time as a Long."
478 try:
479 s = _os_stat(pathname)
480 except OSError:
481 return None
482 return long(s[8])
Greg Stein63faa011999-11-20 11:22:37 +0000483
Greg Stein63faa011999-11-20 11:22:37 +0000484
485######################################################################
486#
487# Emulate the import mechanism for builtin and frozen modules
488#
489class BuiltinImporter(Importer):
Greg Steindd6eefb2000-07-18 09:09:48 +0000490 def get_code(self, parent, modname, fqname):
491 if parent:
492 # these modules definitely do not occur within a package context
493 return None
Greg Stein63faa011999-11-20 11:22:37 +0000494
Greg Steindd6eefb2000-07-18 09:09:48 +0000495 # look for the module
496 if imp.is_builtin(modname):
497 type = imp.C_BUILTIN
498 elif imp.is_frozen(modname):
499 type = imp.PY_FROZEN
500 else:
501 # not found
502 return None
Greg Stein63faa011999-11-20 11:22:37 +0000503
Greg Steindd6eefb2000-07-18 09:09:48 +0000504 # got it. now load and return it.
505 module = imp.load_module(modname, None, modname, ('', '', type))
506 return 0, module, { }
Greg Stein63faa011999-11-20 11:22:37 +0000507
508
509######################################################################
Greg Steinf23aa1e2000-01-03 02:38:29 +0000510#
511# Internal importer used for importing from the filesystem
512#
513class _FilesystemImporter(Importer):
Greg Steindd6eefb2000-07-18 09:09:48 +0000514 def __init__(self):
515 self.suffixes = [ ]
Greg Stein3bb578c2000-02-18 13:04:10 +0000516
Greg Steindd6eefb2000-07-18 09:09:48 +0000517 def add_suffix(self, suffix, importFunc):
518 assert callable(importFunc)
519 self.suffixes.append((suffix, importFunc))
Greg Steinf23aa1e2000-01-03 02:38:29 +0000520
Greg Steindd6eefb2000-07-18 09:09:48 +0000521 def import_from_dir(self, dir, fqname):
522 result = self._import_pathname(_os_path_join(dir, fqname), fqname)
523 if result:
524 return self._process_result(result, fqname)
525 return None
Greg Steinf23aa1e2000-01-03 02:38:29 +0000526
Greg Steindd6eefb2000-07-18 09:09:48 +0000527 def get_code(self, parent, modname, fqname):
528 # This importer is never used with an empty parent. Its existence is
529 # private to the ImportManager. The ImportManager uses the
530 # import_from_dir() method to import top-level modules/packages.
531 # This method is only used when we look for a module within a package.
532 assert parent
Greg Steinf23aa1e2000-01-03 02:38:29 +0000533
Greg Steindd6eefb2000-07-18 09:09:48 +0000534 return self._import_pathname(_os_path_join(parent.__pkgdir__, modname),
Greg Steinf23aa1e2000-01-03 02:38:29 +0000535 fqname)
Greg Steinf23aa1e2000-01-03 02:38:29 +0000536
Greg Steindd6eefb2000-07-18 09:09:48 +0000537 def _import_pathname(self, pathname, fqname):
538 if _os_path_isdir(pathname):
539 result = self._import_pathname(_os_path_join(pathname, '__init__'),
540 fqname)
541 if result:
542 values = result[2]
543 values['__pkgdir__'] = pathname
544 values['__path__'] = [ pathname ]
545 return 1, result[1], values
546 return None
547
548 for suffix, importFunc in self.suffixes:
549 filename = pathname + suffix
550 try:
551 finfo = _os_stat(filename)
552 except OSError:
553 pass
554 else:
555 return importFunc(filename, finfo, fqname)
556 return None
Greg Steinf23aa1e2000-01-03 02:38:29 +0000557
558######################################################################
559#
560# SUFFIX-BASED IMPORTERS
561#
562
Greg Stein3bb578c2000-02-18 13:04:10 +0000563def py_suffix_importer(filename, finfo, fqname):
Greg Steindd6eefb2000-07-18 09:09:48 +0000564 file = filename[:-3] + _suffix
565 t_py = long(finfo[8])
566 t_pyc = _timestamp(file)
Greg Steinf23aa1e2000-01-03 02:38:29 +0000567
Greg Steindd6eefb2000-07-18 09:09:48 +0000568 code = None
569 if t_pyc is not None and t_pyc >= t_py:
570 f = open(file, 'rb')
571 if f.read(4) == imp.get_magic():
572 t = struct.unpack('<I', f.read(4))[0]
573 if t == t_py:
574 code = marshal.load(f)
575 f.close()
576 if code is None:
577 file = filename
578 code = _compile(file, t_py)
Greg Steinf23aa1e2000-01-03 02:38:29 +0000579
Greg Steindd6eefb2000-07-18 09:09:48 +0000580 return 0, code, { '__file__' : file }
Greg Steinf23aa1e2000-01-03 02:38:29 +0000581
Greg Stein3bb578c2000-02-18 13:04:10 +0000582class DynLoadSuffixImporter:
Greg Steindd6eefb2000-07-18 09:09:48 +0000583 def __init__(self, desc):
584 self.desc = desc
Greg Steinf23aa1e2000-01-03 02:38:29 +0000585
Greg Steindd6eefb2000-07-18 09:09:48 +0000586 def import_file(self, filename, finfo, fqname):
587 fp = open(filename, self.desc[1])
588 module = imp.load_module(fqname, fp, filename, self.desc)
589 module.__file__ = filename
590 return 0, module, { }
Greg Steinf23aa1e2000-01-03 02:38:29 +0000591
592
593######################################################################
Greg Stein63faa011999-11-20 11:22:37 +0000594
Greg Stein63faa011999-11-20 11:22:37 +0000595def _print_importers():
Greg Steindd6eefb2000-07-18 09:09:48 +0000596 items = sys.modules.items()
597 items.sort()
598 for name, module in items:
599 if module:
600 print name, module.__dict__.get('__importer__', '-- no importer')
601 else:
602 print name, '-- non-existent module'
Greg Stein63faa011999-11-20 11:22:37 +0000603
Greg Steinf23aa1e2000-01-03 02:38:29 +0000604def _test_revamp():
Greg Steindd6eefb2000-07-18 09:09:48 +0000605 ImportManager().install()
606 sys.path.insert(0, BuiltinImporter())
Greg Steinf23aa1e2000-01-03 02:38:29 +0000607
Greg Stein281b8d81999-11-07 12:54:45 +0000608######################################################################
Greg Stein42b9bc72000-02-19 13:36:23 +0000609
610#
611# TODO
612#
613# from Finn Bock:
Greg Stein42b9bc72000-02-19 13:36:23 +0000614# type(sys) is not a module in JPython. what to use instead?
615# imp.C_EXTENSION is not in JPython. same for get_suffixes and new_module
616#
617# given foo.py of:
618# import sys
619# sys.modules['foo'] = sys
620#
621# ---- standard import mechanism
622# >>> import foo
623# >>> foo
624# <module 'sys' (built-in)>
625#
626# ---- revamped import mechanism
627# >>> import imputil
628# >>> imputil._test_revamp()
629# >>> import foo
630# >>> foo
631# <module 'foo' from 'foo.py'>
632#
633#
634# from MAL:
635# should BuiltinImporter exist in sys.path or hard-wired in ImportManager?
636# need __path__ processing
637# performance
638# move chaining to a subclass [gjs: it's been nuked]
Greg Stein42b9bc72000-02-19 13:36:23 +0000639# deinstall should be possible
640# query mechanism needed: is a specific Importer installed?
641# py/pyc/pyo piping hooks to filter/process these files
642# wish list:
643# distutils importer hooked to list of standard Internet repositories
644# module->file location mapper to speed FS-based imports
645# relative imports
646# keep chaining so that it can play nice with other import hooks
647#
648# from Gordon:
649# push MAL's mapper into sys.path[0] as a cache (hard-coded for apps)
650#
651# from Guido:
652# need to change sys.* references for rexec environs
653# need hook for MAL's walk-me-up import strategy, or Tim's absolute strategy
Fred Drake8152d322000-12-12 23:20:45 +0000654# watch out for sys.modules[...] is None
Greg Stein42b9bc72000-02-19 13:36:23 +0000655# flag to force absolute imports? (speeds _determine_import_context and
656# checking for a relative module)
657# insert names of archives into sys.path (see quote below)
658# note: reload does NOT blast module dict
659# shift import mechanisms and policies around; provide for hooks, overrides
660# (see quote below)
661# add get_source stuff
662# get_topcode and get_subcode
663# CRLF handling in _compile
664# race condition in _compile
665# refactoring of os.py to deal with _os_bootstrap problem
666# any special handling to do for importing a module with a SyntaxError?
667# (e.g. clean up the traceback)
668# implement "domain" for path-type functionality using pkg namespace
669# (rather than FS-names like __path__)
670# don't use the word "private"... maybe "internal"
671#
672#
673# Guido's comments on sys.path caching:
Tim Peters07e99cb2001-01-14 23:47:14 +0000674#
Greg Stein42b9bc72000-02-19 13:36:23 +0000675# We could cache this in a dictionary: the ImportManager can have a
676# cache dict mapping pathnames to importer objects, and a separate
677# method for coming up with an importer given a pathname that's not yet
678# in the cache. The method should do a stat and/or look at the
679# extension to decide which importer class to use; you can register new
680# importer classes by registering a suffix or a Boolean function, plus a
681# class. If you register a new importer class, the cache is zapped.
682# The cache is independent from sys.path (but maintained per
683# ImportManager instance) so that rearrangements of sys.path do the
684# right thing. If a path is dropped from sys.path the corresponding
685# cache entry is simply no longer used.
686#
687# My/Guido's comments on factoring ImportManager and Importer:
688#
689# > However, we still have a tension occurring here:
Tim Peters07e99cb2001-01-14 23:47:14 +0000690# >
Greg Stein42b9bc72000-02-19 13:36:23 +0000691# > 1) implementing policy in ImportManager assists in single-point policy
692# > changes for app/rexec situations
693# > 2) implementing policy in Importer assists in package-private policy
694# > changes for normal, operating conditions
Tim Peters07e99cb2001-01-14 23:47:14 +0000695# >
Greg Stein42b9bc72000-02-19 13:36:23 +0000696# > I'll see if I can sort out a way to do this. Maybe the Importer class will
697# > implement the methods (which can be overridden to change policy) by
698# > delegating to ImportManager.
Tim Peters07e99cb2001-01-14 23:47:14 +0000699#
Greg Stein42b9bc72000-02-19 13:36:23 +0000700# Maybe also think about what kind of policies an Importer would be
701# likely to want to change. I have a feeling that a lot of the code
702# there is actually not so much policy but a *necessity* to get things
703# working given the calling conventions for the __import__ hook: whether
704# to return the head or tail of a dotted name, or when to do the "finish
705# fromlist" stuff.
706#