blob: 3185d7d94cc1c82b33f345edb15e64953a4e1b9d [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
10import strop
Greg Stein7ec28d21999-11-20 12:31:07 +000011import __builtin__
Greg Stein281b8d81999-11-07 12:54:45 +000012
13# for the DirectoryImporter
14import struct
15import marshal
16
Skip Montanaro17ab1232001-01-24 06:27:27 +000017__all__ = ["ImportManager","Importer","BuiltinImporter"]
18
Greg Steinf23aa1e2000-01-03 02:38:29 +000019_StringType = type('')
Tim Peters07e99cb2001-01-14 23:47:14 +000020_ModuleType = type(sys) ### doesn't work in JPython...
Greg Steinf23aa1e2000-01-03 02:38:29 +000021
22class ImportManager:
Greg Steindd6eefb2000-07-18 09:09:48 +000023 "Manage the import process."
Greg Stein281b8d81999-11-07 12:54:45 +000024
Greg Steindd6eefb2000-07-18 09:09:48 +000025 def install(self, namespace=vars(__builtin__)):
26 "Install this ImportManager into the specified namespace."
Greg Steind4f1d202000-02-18 12:03:40 +000027
Greg Steindd6eefb2000-07-18 09:09:48 +000028 if isinstance(namespace, _ModuleType):
29 namespace = vars(namespace)
Greg Steind4f1d202000-02-18 12:03:40 +000030
Greg Steindd6eefb2000-07-18 09:09:48 +000031 ### Note that we have no notion of "uninstall" or "chaining"
Greg Stein3bb578c2000-02-18 13:04:10 +000032
Greg Steindd6eefb2000-07-18 09:09:48 +000033 namespace['__import__'] = self._import_hook
34 ### fix this
35 #namespace['reload'] = self._reload_hook
Greg Steinf23aa1e2000-01-03 02:38:29 +000036
Greg Steindd6eefb2000-07-18 09:09:48 +000037 def add_suffix(self, suffix, importFunc):
38 assert callable(importFunc)
39 self.fs_imp.add_suffix(suffix, importFunc)
Greg Stein281b8d81999-11-07 12:54:45 +000040
Greg Steindd6eefb2000-07-18 09:09:48 +000041 ######################################################################
42 #
43 # PRIVATE METHODS
44 #
Greg Stein3bb578c2000-02-18 13:04:10 +000045
Greg Steindd6eefb2000-07-18 09:09:48 +000046 clsFilesystemImporter = None
Greg Stein281b8d81999-11-07 12:54:45 +000047
Greg Steindd6eefb2000-07-18 09:09:48 +000048 def __init__(self, fs_imp=None):
49 # we're definitely going to be importing something in the future,
50 # so let's just load the OS-related facilities.
51 if not _os_stat:
52 _os_bootstrap()
Greg Stein3bb578c2000-02-18 13:04:10 +000053
Greg Steindd6eefb2000-07-18 09:09:48 +000054 # This is the Importer that we use for grabbing stuff from the
55 # filesystem. It defines one more method (import_from_dir) for our use.
56 if not fs_imp:
57 cls = self.clsFilesystemImporter or _FilesystemImporter
58 fs_imp = cls()
59 self.fs_imp = fs_imp
Greg Stein281b8d81999-11-07 12:54:45 +000060
Greg Steindd6eefb2000-07-18 09:09:48 +000061 # Initialize the set of suffixes that we recognize and import.
62 # The default will import dynamic-load modules first, followed by
63 # .py files (or a .py file's cached bytecode)
64 for desc in imp.get_suffixes():
65 if desc[2] == imp.C_EXTENSION:
66 self.add_suffix(desc[0],
67 DynLoadSuffixImporter(desc).import_file)
68 self.add_suffix('.py', py_suffix_importer)
Greg Steinf23aa1e2000-01-03 02:38:29 +000069
Greg Steindd6eefb2000-07-18 09:09:48 +000070 def _import_hook(self, fqname, globals=None, locals=None, fromlist=None):
71 """Python calls this hook to locate and import a module."""
Greg Stein63faa011999-11-20 11:22:37 +000072
Greg Steindd6eefb2000-07-18 09:09:48 +000073 parts = strop.split(fqname, '.')
Greg Stein281b8d81999-11-07 12:54:45 +000074
Greg Steindd6eefb2000-07-18 09:09:48 +000075 # determine the context of this import
76 parent = self._determine_import_context(globals)
Greg Stein281b8d81999-11-07 12:54:45 +000077
Greg Steindd6eefb2000-07-18 09:09:48 +000078 # if there is a parent, then its importer should manage this import
79 if parent:
80 module = parent.__importer__._do_import(parent, parts, fromlist)
81 if module:
82 return module
Greg Stein281b8d81999-11-07 12:54:45 +000083
Greg Steindd6eefb2000-07-18 09:09:48 +000084 # has the top module already been imported?
85 try:
86 top_module = sys.modules[parts[0]]
87 except KeyError:
88
89 # look for the topmost module
90 top_module = self._import_top_module(parts[0])
91 if not top_module:
92 # the topmost module wasn't found at all.
93 raise ImportError, 'No module named ' + fqname
94
95 # fast-path simple imports
96 if len(parts) == 1:
97 if not fromlist:
98 return top_module
99
100 if not top_module.__dict__.get('__ispkg__'):
101 # __ispkg__ isn't defined (the module was not imported by us),
102 # or it is zero.
103 #
104 # In the former case, there is no way that we could import
105 # sub-modules that occur in the fromlist (but we can't raise an
106 # error because it may just be names) because we don't know how
107 # to deal with packages that were imported by other systems.
108 #
109 # In the latter case (__ispkg__ == 0), there can't be any sub-
110 # modules present, so we can just return.
111 #
112 # In both cases, since len(parts) == 1, the top_module is also
113 # the "bottom" which is the defined return when a fromlist
114 # exists.
115 return top_module
116
117 importer = top_module.__dict__.get('__importer__')
118 if importer:
119 return importer._finish_import(top_module, parts[1:], fromlist)
120
121 # If the importer does not exist, then we have to bail. A missing
122 # importer means that something else imported the module, and we have
123 # no knowledge of how to get sub-modules out of the thing.
Greg Steinf23aa1e2000-01-03 02:38:29 +0000124 raise ImportError, 'No module named ' + fqname
Greg Steinf23aa1e2000-01-03 02:38:29 +0000125
Greg Steindd6eefb2000-07-18 09:09:48 +0000126 def _determine_import_context(self, globals):
127 """Returns the context in which a module should be imported.
Greg Steinf23aa1e2000-01-03 02:38:29 +0000128
Greg Steindd6eefb2000-07-18 09:09:48 +0000129 The context could be a loaded (package) module and the imported module
130 will be looked for within that package. The context could also be None,
131 meaning there is no context -- the module should be looked for as a
132 "top-level" module.
133 """
Greg Steinf23aa1e2000-01-03 02:38:29 +0000134
Greg Steindd6eefb2000-07-18 09:09:48 +0000135 if not globals or not globals.get('__importer__'):
136 # globals does not refer to one of our modules or packages. That
137 # implies there is no relative import context (as far as we are
138 # concerned), and it should just pick it off the standard path.
139 return None
Greg Steinf23aa1e2000-01-03 02:38:29 +0000140
Greg Steindd6eefb2000-07-18 09:09:48 +0000141 # The globals refer to a module or package of ours. It will define
142 # the context of the new import. Get the module/package fqname.
143 parent_fqname = globals['__name__']
Greg Steinf23aa1e2000-01-03 02:38:29 +0000144
Greg Steindd6eefb2000-07-18 09:09:48 +0000145 # if a package is performing the import, then return itself (imports
146 # refer to pkg contents)
147 if globals['__ispkg__']:
148 parent = sys.modules[parent_fqname]
149 assert globals is parent.__dict__
150 return parent
Greg Steinf23aa1e2000-01-03 02:38:29 +0000151
Greg Steindd6eefb2000-07-18 09:09:48 +0000152 i = strop.rfind(parent_fqname, '.')
Greg Steinf23aa1e2000-01-03 02:38:29 +0000153
Greg Steindd6eefb2000-07-18 09:09:48 +0000154 # a module outside of a package has no particular import context
155 if i == -1:
156 return None
Greg Steinf23aa1e2000-01-03 02:38:29 +0000157
Greg Steindd6eefb2000-07-18 09:09:48 +0000158 # if a module in a package is performing the import, then return the
159 # package (imports refer to siblings)
160 parent_fqname = parent_fqname[:i]
161 parent = sys.modules[parent_fqname]
162 assert parent.__name__ == parent_fqname
163 return parent
Greg Steinf23aa1e2000-01-03 02:38:29 +0000164
Greg Steindd6eefb2000-07-18 09:09:48 +0000165 def _import_top_module(self, name):
166 # scan sys.path looking for a location in the filesystem that contains
167 # the module, or an Importer object that can import the module.
168 for item in sys.path:
169 if isinstance(item, _StringType):
170 module = self.fs_imp.import_from_dir(item, name)
171 else:
172 module = item.import_top(name)
173 if module:
174 return module
175 return None
Greg Steinf23aa1e2000-01-03 02:38:29 +0000176
Greg Steindd6eefb2000-07-18 09:09:48 +0000177 def _reload_hook(self, module):
178 "Python calls this hook to reload a module."
Greg Steinf23aa1e2000-01-03 02:38:29 +0000179
Greg Steindd6eefb2000-07-18 09:09:48 +0000180 # reloading of a module may or may not be possible (depending on the
181 # importer), but at least we can validate that it's ours to reload
182 importer = module.__dict__.get('__importer__')
183 if not importer:
184 ### oops. now what...
185 pass
Greg Steinf23aa1e2000-01-03 02:38:29 +0000186
Greg Steindd6eefb2000-07-18 09:09:48 +0000187 # okay. it is using the imputil system, and we must delegate it, but
188 # we don't know what to do (yet)
189 ### we should blast the module dict and do another get_code(). need to
190 ### flesh this out and add proper docco...
191 raise SystemError, "reload not yet implemented"
Greg Steinf23aa1e2000-01-03 02:38:29 +0000192
193
194class Importer:
Greg Steindd6eefb2000-07-18 09:09:48 +0000195 "Base class for replacing standard import functions."
Greg Steinf23aa1e2000-01-03 02:38:29 +0000196
Greg Steindd6eefb2000-07-18 09:09:48 +0000197 def import_top(self, name):
198 "Import a top-level module."
199 return self._import_one(None, name, name)
Greg Steinf23aa1e2000-01-03 02:38:29 +0000200
Greg Steindd6eefb2000-07-18 09:09:48 +0000201 ######################################################################
Greg Stein281b8d81999-11-07 12:54:45 +0000202 #
Greg Steindd6eefb2000-07-18 09:09:48 +0000203 # PRIVATE METHODS
Greg Stein281b8d81999-11-07 12:54:45 +0000204 #
Greg Steindd6eefb2000-07-18 09:09:48 +0000205 def _finish_import(self, top, parts, fromlist):
206 # if "a.b.c" was provided, then load the ".b.c" portion down from
207 # below the top-level module.
208 bottom = self._load_tail(top, parts)
Greg Stein281b8d81999-11-07 12:54:45 +0000209
Greg Steindd6eefb2000-07-18 09:09:48 +0000210 # if the form is "import a.b.c", then return "a"
211 if not fromlist:
212 # no fromlist: return the top of the import tree
213 return top
214
215 # the top module was imported by self.
216 #
217 # this means that the bottom module was also imported by self (just
218 # now, or in the past and we fetched it from sys.modules).
219 #
220 # since we imported/handled the bottom module, this means that we can
221 # also handle its fromlist (and reliably use __ispkg__).
222
223 # if the bottom node is a package, then (potentially) import some
224 # modules.
225 #
226 # note: if it is not a package, then "fromlist" refers to names in
227 # the bottom module rather than modules.
228 # note: for a mix of names and modules in the fromlist, we will
229 # import all modules and insert those into the namespace of
230 # the package module. Python will pick up all fromlist names
231 # from the bottom (package) module; some will be modules that
232 # we imported and stored in the namespace, others are expected
233 # to be present already.
234 if bottom.__ispkg__:
235 self._import_fromlist(bottom, fromlist)
236
237 # if the form is "from a.b import c, d" then return "b"
238 return bottom
239
240 def _import_one(self, parent, modname, fqname):
241 "Import a single module."
242
243 # has the module already been imported?
244 try:
245 return sys.modules[fqname]
246 except KeyError:
247 pass
248
249 # load the module's code, or fetch the module itself
250 result = self.get_code(parent, modname, fqname)
251 if result is None:
252 return None
253
254 module = self._process_result(result, fqname)
255
256 # insert the module into its parent
257 if parent:
258 setattr(parent, modname, module)
259 return module
260
261 def _process_result(self, (ispkg, code, values), fqname):
262 # did get_code() return an actual module? (rather than a code object)
263 is_module = isinstance(code, _ModuleType)
264
265 # use the returned module, or create a new one to exec code into
266 if is_module:
267 module = code
268 else:
269 module = imp.new_module(fqname)
270
271 ### record packages a bit differently??
272 module.__importer__ = self
273 module.__ispkg__ = ispkg
274
275 # insert additional values into the module (before executing the code)
276 module.__dict__.update(values)
277
278 # the module is almost ready... make it visible
279 sys.modules[fqname] = module
280
281 # execute the code within the module's namespace
282 if not is_module:
283 exec code in module.__dict__
284
285 return module
286
287 def _load_tail(self, m, parts):
288 """Import the rest of the modules, down from the top-level module.
289
290 Returns the last module in the dotted list of modules.
291 """
292 for part in parts:
293 fqname = "%s.%s" % (m.__name__, part)
294 m = self._import_one(m, part, fqname)
295 if not m:
296 raise ImportError, "No module named " + fqname
297 return m
298
299 def _import_fromlist(self, package, fromlist):
300 'Import any sub-modules in the "from" list.'
301
302 # if '*' is present in the fromlist, then look for the '__all__'
303 # variable to find additional items (modules) to import.
304 if '*' in fromlist:
305 fromlist = list(fromlist) + \
306 list(package.__dict__.get('__all__', []))
307
308 for sub in fromlist:
309 # if the name is already present, then don't try to import it (it
310 # might not be a module!).
311 if sub != '*' and not hasattr(package, sub):
312 subname = "%s.%s" % (package.__name__, sub)
313 submod = self._import_one(package, sub, subname)
314 if not submod:
315 raise ImportError, "cannot import name " + subname
316
317 def _do_import(self, parent, parts, fromlist):
318 """Attempt to import the module relative to parent.
319
320 This method is used when the import context specifies that <self>
321 imported the parent module.
322 """
323 top_name = parts[0]
324 top_fqname = parent.__name__ + '.' + top_name
325 top_module = self._import_one(parent, top_name, top_fqname)
326 if not top_module:
327 # this importer and parent could not find the module (relatively)
328 return None
329
330 return self._finish_import(top_module, parts[1:], fromlist)
331
332 ######################################################################
Greg Stein281b8d81999-11-07 12:54:45 +0000333 #
Greg Steindd6eefb2000-07-18 09:09:48 +0000334 # METHODS TO OVERRIDE
335 #
336 def get_code(self, parent, modname, fqname):
337 """Find and retrieve the code for the given module.
Greg Stein281b8d81999-11-07 12:54:45 +0000338
Greg Steindd6eefb2000-07-18 09:09:48 +0000339 parent specifies a parent module to define a context for importing. It
340 may be None, indicating no particular context for the search.
Greg Stein281b8d81999-11-07 12:54:45 +0000341
Greg Steindd6eefb2000-07-18 09:09:48 +0000342 modname specifies a single module (not dotted) within the parent.
Greg Stein281b8d81999-11-07 12:54:45 +0000343
Greg Steindd6eefb2000-07-18 09:09:48 +0000344 fqname specifies the fully-qualified module name. This is a
345 (potentially) dotted name from the "root" of the module namespace
346 down to the modname.
347 If there is no parent, then modname==fqname.
Greg Stein281b8d81999-11-07 12:54:45 +0000348
Greg Steindd6eefb2000-07-18 09:09:48 +0000349 This method should return None, or a 3-tuple.
Greg Stein281b8d81999-11-07 12:54:45 +0000350
Greg Steindd6eefb2000-07-18 09:09:48 +0000351 * If the module was not found, then None should be returned.
Greg Stein281b8d81999-11-07 12:54:45 +0000352
Greg Steindd6eefb2000-07-18 09:09:48 +0000353 * The first item of the 2- or 3-tuple should be the integer 0 or 1,
354 specifying whether the module that was found is a package or not.
Greg Stein281b8d81999-11-07 12:54:45 +0000355
Greg Steindd6eefb2000-07-18 09:09:48 +0000356 * The second item is the code object for the module (it will be
357 executed within the new module's namespace). This item can also
358 be a fully-loaded module object (e.g. loaded from a shared lib).
Greg Steinf23aa1e2000-01-03 02:38:29 +0000359
Greg Steindd6eefb2000-07-18 09:09:48 +0000360 * The third item is a dictionary of name/value pairs that will be
361 inserted into new module before the code object is executed. This
362 is provided in case the module's code expects certain values (such
363 as where the module was found). When the second item is a module
364 object, then these names/values will be inserted *after* the module
365 has been loaded/initialized.
366 """
367 raise RuntimeError, "get_code not implemented"
Greg Stein281b8d81999-11-07 12:54:45 +0000368
369
370######################################################################
371#
Greg Stein63faa011999-11-20 11:22:37 +0000372# Some handy stuff for the Importers
373#
374
Greg Steind4f1d202000-02-18 12:03:40 +0000375# byte-compiled file suffix character
Greg Stein63faa011999-11-20 11:22:37 +0000376_suffix_char = __debug__ and 'c' or 'o'
377
378# byte-compiled file suffix
379_suffix = '.py' + _suffix_char
380
Greg Stein63faa011999-11-20 11:22:37 +0000381def _compile(pathname, timestamp):
Greg Steindd6eefb2000-07-18 09:09:48 +0000382 """Compile (and cache) a Python source file.
Greg Stein63faa011999-11-20 11:22:37 +0000383
Greg Steindd6eefb2000-07-18 09:09:48 +0000384 The file specified by <pathname> is compiled to a code object and
385 returned.
Greg Stein63faa011999-11-20 11:22:37 +0000386
Greg Steindd6eefb2000-07-18 09:09:48 +0000387 Presuming the appropriate privileges exist, the bytecodes will be
388 saved back to the filesystem for future imports. The source file's
389 modification timestamp must be provided as a Long value.
390 """
391 codestring = open(pathname, 'r').read()
392 if codestring and codestring[-1] != '\n':
393 codestring = codestring + '\n'
394 code = __builtin__.compile(codestring, pathname, 'exec')
Greg Stein63faa011999-11-20 11:22:37 +0000395
Greg Steindd6eefb2000-07-18 09:09:48 +0000396 # try to cache the compiled code
397 try:
398 f = open(pathname + _suffix_char, 'wb')
399 except IOError:
400 pass
401 else:
402 f.write('\0\0\0\0')
403 f.write(struct.pack('<I', timestamp))
404 marshal.dump(code, f)
405 f.flush()
406 f.seek(0, 0)
407 f.write(imp.get_magic())
408 f.close()
Greg Stein63faa011999-11-20 11:22:37 +0000409
Greg Steindd6eefb2000-07-18 09:09:48 +0000410 return code
Greg Stein63faa011999-11-20 11:22:37 +0000411
412_os_stat = _os_path_join = None
413def _os_bootstrap():
Greg Steindd6eefb2000-07-18 09:09:48 +0000414 "Set up 'os' module replacement functions for use during import bootstrap."
Greg Stein63faa011999-11-20 11:22:37 +0000415
Greg Steindd6eefb2000-07-18 09:09:48 +0000416 names = sys.builtin_module_names
Greg Stein63faa011999-11-20 11:22:37 +0000417
Greg Steindd6eefb2000-07-18 09:09:48 +0000418 join = None
419 if 'posix' in names:
420 sep = '/'
421 from posix import stat
422 elif 'nt' in names:
423 sep = '\\'
424 from nt import stat
425 elif 'dos' in names:
426 sep = '\\'
427 from dos import stat
428 elif 'os2' in names:
429 sep = '\\'
430 from os2 import stat
431 elif 'mac' in names:
432 from mac import stat
433 def join(a, b):
434 if a == '':
435 return b
436 path = s
437 if ':' not in a:
438 a = ':' + a
Fred Drake8152d322000-12-12 23:20:45 +0000439 if a[-1:] != ':':
Greg Steindd6eefb2000-07-18 09:09:48 +0000440 a = a + ':'
441 return a + b
442 else:
443 raise ImportError, 'no os specific module found'
Greg Stein63faa011999-11-20 11:22:37 +0000444
Greg Steindd6eefb2000-07-18 09:09:48 +0000445 if join is None:
446 def join(a, b, sep=sep):
447 if a == '':
448 return b
449 lastchar = a[-1:]
450 if lastchar == '/' or lastchar == sep:
451 return a + b
452 return a + sep + b
Greg Stein63faa011999-11-20 11:22:37 +0000453
Greg Steindd6eefb2000-07-18 09:09:48 +0000454 global _os_stat
455 _os_stat = stat
456
457 global _os_path_join
458 _os_path_join = join
Greg Stein63faa011999-11-20 11:22:37 +0000459
460def _os_path_isdir(pathname):
Greg Steindd6eefb2000-07-18 09:09:48 +0000461 "Local replacement for os.path.isdir()."
462 try:
463 s = _os_stat(pathname)
464 except OSError:
465 return None
466 return (s[0] & 0170000) == 0040000
Greg Stein63faa011999-11-20 11:22:37 +0000467
468def _timestamp(pathname):
Greg Steindd6eefb2000-07-18 09:09:48 +0000469 "Return the file modification time as a Long."
470 try:
471 s = _os_stat(pathname)
472 except OSError:
473 return None
474 return long(s[8])
Greg Stein63faa011999-11-20 11:22:37 +0000475
Greg Stein63faa011999-11-20 11:22:37 +0000476
477######################################################################
478#
479# Emulate the import mechanism for builtin and frozen modules
480#
481class BuiltinImporter(Importer):
Greg Steindd6eefb2000-07-18 09:09:48 +0000482 def get_code(self, parent, modname, fqname):
483 if parent:
484 # these modules definitely do not occur within a package context
485 return None
Greg Stein63faa011999-11-20 11:22:37 +0000486
Greg Steindd6eefb2000-07-18 09:09:48 +0000487 # look for the module
488 if imp.is_builtin(modname):
489 type = imp.C_BUILTIN
490 elif imp.is_frozen(modname):
491 type = imp.PY_FROZEN
492 else:
493 # not found
494 return None
Greg Stein63faa011999-11-20 11:22:37 +0000495
Greg Steindd6eefb2000-07-18 09:09:48 +0000496 # got it. now load and return it.
497 module = imp.load_module(modname, None, modname, ('', '', type))
498 return 0, module, { }
Greg Stein63faa011999-11-20 11:22:37 +0000499
500
501######################################################################
Greg Steinf23aa1e2000-01-03 02:38:29 +0000502#
503# Internal importer used for importing from the filesystem
504#
505class _FilesystemImporter(Importer):
Greg Steindd6eefb2000-07-18 09:09:48 +0000506 def __init__(self):
507 self.suffixes = [ ]
Greg Stein3bb578c2000-02-18 13:04:10 +0000508
Greg Steindd6eefb2000-07-18 09:09:48 +0000509 def add_suffix(self, suffix, importFunc):
510 assert callable(importFunc)
511 self.suffixes.append((suffix, importFunc))
Greg Steinf23aa1e2000-01-03 02:38:29 +0000512
Greg Steindd6eefb2000-07-18 09:09:48 +0000513 def import_from_dir(self, dir, fqname):
514 result = self._import_pathname(_os_path_join(dir, fqname), fqname)
515 if result:
516 return self._process_result(result, fqname)
517 return None
Greg Steinf23aa1e2000-01-03 02:38:29 +0000518
Greg Steindd6eefb2000-07-18 09:09:48 +0000519 def get_code(self, parent, modname, fqname):
520 # This importer is never used with an empty parent. Its existence is
521 # private to the ImportManager. The ImportManager uses the
522 # import_from_dir() method to import top-level modules/packages.
523 # This method is only used when we look for a module within a package.
524 assert parent
Greg Steinf23aa1e2000-01-03 02:38:29 +0000525
Greg Steindd6eefb2000-07-18 09:09:48 +0000526 return self._import_pathname(_os_path_join(parent.__pkgdir__, modname),
Greg Steinf23aa1e2000-01-03 02:38:29 +0000527 fqname)
Greg Steinf23aa1e2000-01-03 02:38:29 +0000528
Greg Steindd6eefb2000-07-18 09:09:48 +0000529 def _import_pathname(self, pathname, fqname):
530 if _os_path_isdir(pathname):
531 result = self._import_pathname(_os_path_join(pathname, '__init__'),
532 fqname)
533 if result:
534 values = result[2]
535 values['__pkgdir__'] = pathname
536 values['__path__'] = [ pathname ]
537 return 1, result[1], values
538 return None
539
540 for suffix, importFunc in self.suffixes:
541 filename = pathname + suffix
542 try:
543 finfo = _os_stat(filename)
544 except OSError:
545 pass
546 else:
547 return importFunc(filename, finfo, fqname)
548 return None
Greg Steinf23aa1e2000-01-03 02:38:29 +0000549
550######################################################################
551#
552# SUFFIX-BASED IMPORTERS
553#
554
Greg Stein3bb578c2000-02-18 13:04:10 +0000555def py_suffix_importer(filename, finfo, fqname):
Greg Steindd6eefb2000-07-18 09:09:48 +0000556 file = filename[:-3] + _suffix
557 t_py = long(finfo[8])
558 t_pyc = _timestamp(file)
Greg Steinf23aa1e2000-01-03 02:38:29 +0000559
Greg Steindd6eefb2000-07-18 09:09:48 +0000560 code = None
561 if t_pyc is not None and t_pyc >= t_py:
562 f = open(file, 'rb')
563 if f.read(4) == imp.get_magic():
564 t = struct.unpack('<I', f.read(4))[0]
565 if t == t_py:
566 code = marshal.load(f)
567 f.close()
568 if code is None:
569 file = filename
570 code = _compile(file, t_py)
Greg Steinf23aa1e2000-01-03 02:38:29 +0000571
Greg Steindd6eefb2000-07-18 09:09:48 +0000572 return 0, code, { '__file__' : file }
Greg Steinf23aa1e2000-01-03 02:38:29 +0000573
Greg Stein3bb578c2000-02-18 13:04:10 +0000574class DynLoadSuffixImporter:
Greg Steindd6eefb2000-07-18 09:09:48 +0000575 def __init__(self, desc):
576 self.desc = desc
Greg Steinf23aa1e2000-01-03 02:38:29 +0000577
Greg Steindd6eefb2000-07-18 09:09:48 +0000578 def import_file(self, filename, finfo, fqname):
579 fp = open(filename, self.desc[1])
580 module = imp.load_module(fqname, fp, filename, self.desc)
581 module.__file__ = filename
582 return 0, module, { }
Greg Steinf23aa1e2000-01-03 02:38:29 +0000583
584
585######################################################################
Greg Stein63faa011999-11-20 11:22:37 +0000586
Greg Stein63faa011999-11-20 11:22:37 +0000587def _print_importers():
Greg Steindd6eefb2000-07-18 09:09:48 +0000588 items = sys.modules.items()
589 items.sort()
590 for name, module in items:
591 if module:
592 print name, module.__dict__.get('__importer__', '-- no importer')
593 else:
594 print name, '-- non-existent module'
Greg Stein63faa011999-11-20 11:22:37 +0000595
Greg Steinf23aa1e2000-01-03 02:38:29 +0000596def _test_revamp():
Greg Steindd6eefb2000-07-18 09:09:48 +0000597 ImportManager().install()
598 sys.path.insert(0, BuiltinImporter())
Greg Steinf23aa1e2000-01-03 02:38:29 +0000599
Greg Stein281b8d81999-11-07 12:54:45 +0000600######################################################################
Greg Stein42b9bc72000-02-19 13:36:23 +0000601
602#
603# TODO
604#
605# from Finn Bock:
606# remove use of "strop" -- not available in JPython
607# type(sys) is not a module in JPython. what to use instead?
608# imp.C_EXTENSION is not in JPython. same for get_suffixes and new_module
609#
610# given foo.py of:
611# import sys
612# sys.modules['foo'] = sys
613#
614# ---- standard import mechanism
615# >>> import foo
616# >>> foo
617# <module 'sys' (built-in)>
618#
619# ---- revamped import mechanism
620# >>> import imputil
621# >>> imputil._test_revamp()
622# >>> import foo
623# >>> foo
624# <module 'foo' from 'foo.py'>
625#
626#
627# from MAL:
628# should BuiltinImporter exist in sys.path or hard-wired in ImportManager?
629# need __path__ processing
630# performance
631# move chaining to a subclass [gjs: it's been nuked]
632# avoid strop
633# deinstall should be possible
634# query mechanism needed: is a specific Importer installed?
635# py/pyc/pyo piping hooks to filter/process these files
636# wish list:
637# distutils importer hooked to list of standard Internet repositories
638# module->file location mapper to speed FS-based imports
639# relative imports
640# keep chaining so that it can play nice with other import hooks
641#
642# from Gordon:
643# push MAL's mapper into sys.path[0] as a cache (hard-coded for apps)
644#
645# from Guido:
646# need to change sys.* references for rexec environs
647# need hook for MAL's walk-me-up import strategy, or Tim's absolute strategy
Fred Drake8152d322000-12-12 23:20:45 +0000648# watch out for sys.modules[...] is None
Greg Stein42b9bc72000-02-19 13:36:23 +0000649# flag to force absolute imports? (speeds _determine_import_context and
650# checking for a relative module)
651# insert names of archives into sys.path (see quote below)
652# note: reload does NOT blast module dict
653# shift import mechanisms and policies around; provide for hooks, overrides
654# (see quote below)
655# add get_source stuff
656# get_topcode and get_subcode
657# CRLF handling in _compile
658# race condition in _compile
659# refactoring of os.py to deal with _os_bootstrap problem
660# any special handling to do for importing a module with a SyntaxError?
661# (e.g. clean up the traceback)
662# implement "domain" for path-type functionality using pkg namespace
663# (rather than FS-names like __path__)
664# don't use the word "private"... maybe "internal"
665#
666#
667# Guido's comments on sys.path caching:
Tim Peters07e99cb2001-01-14 23:47:14 +0000668#
Greg Stein42b9bc72000-02-19 13:36:23 +0000669# We could cache this in a dictionary: the ImportManager can have a
670# cache dict mapping pathnames to importer objects, and a separate
671# method for coming up with an importer given a pathname that's not yet
672# in the cache. The method should do a stat and/or look at the
673# extension to decide which importer class to use; you can register new
674# importer classes by registering a suffix or a Boolean function, plus a
675# class. If you register a new importer class, the cache is zapped.
676# The cache is independent from sys.path (but maintained per
677# ImportManager instance) so that rearrangements of sys.path do the
678# right thing. If a path is dropped from sys.path the corresponding
679# cache entry is simply no longer used.
680#
681# My/Guido's comments on factoring ImportManager and Importer:
682#
683# > However, we still have a tension occurring here:
Tim Peters07e99cb2001-01-14 23:47:14 +0000684# >
Greg Stein42b9bc72000-02-19 13:36:23 +0000685# > 1) implementing policy in ImportManager assists in single-point policy
686# > changes for app/rexec situations
687# > 2) implementing policy in Importer assists in package-private policy
688# > changes for normal, operating conditions
Tim Peters07e99cb2001-01-14 23:47:14 +0000689# >
Greg Stein42b9bc72000-02-19 13:36:23 +0000690# > I'll see if I can sort out a way to do this. Maybe the Importer class will
691# > implement the methods (which can be overridden to change policy) by
692# > delegating to ImportManager.
Tim Peters07e99cb2001-01-14 23:47:14 +0000693#
Greg Stein42b9bc72000-02-19 13:36:23 +0000694# Maybe also think about what kind of policies an Importer would be
695# likely to want to change. I have a feeling that a lot of the code
696# there is actually not so much policy but a *necessity* to get things
697# working given the calling conventions for the __import__ hook: whether
698# to return the head or tail of a dotted name, or when to do the "finish
699# fromlist" stuff.
700#