blob: 45c1b0549f468f4a87dac4b17eccc269519ca242 [file] [log] [blame]
Brett Cannon23cbd8a2009-01-18 00:24:28 +00001"""Core implementation of import.
2
3This module is NOT meant to be directly imported! It has been designed such
4that it can be bootstrapped into Python as the implementation of import. As
5such it requires the injection of specific modules and attributes in order to
6work. One should use importlib as the public-facing version of this module.
7
8"""
9
10# Injected modules are '_warnings', 'imp', 'sys', 'marshal', 'errno', and '_os'
11# (a.k.a. 'posix', 'nt' or 'os2').
12# Injected attribute is path_sep.
13#
14# When editing this code be aware that code executed at import time CANNOT
15# reference any injected objects! This includes not only global code but also
16# anything specified at the class level.
17
18
19# XXX Could also expose Modules/getpath.c:joinpath()
20def _path_join(*args):
21 """Replacement for os.path.join."""
22 return path_sep.join(x[:-len(path_sep)] if x.endswith(path_sep) else x
23 for x in args)
24
25
26def _path_exists(path):
27 """Replacement for os.path.exists."""
28 try:
29 _os.stat(path)
30 except OSError:
31 return False
32 else:
33 return True
34
35
36def _path_is_mode_type(path, mode):
37 """Test whether the path is the specified mode type."""
38 try:
39 stat_info = _os.stat(path)
40 except OSError:
41 return False
42 return (stat_info.st_mode & 0o170000) == mode
43
44
45# XXX Could also expose Modules/getpath.c:isfile()
46def _path_isfile(path):
47 """Replacement for os.path.isfile."""
48 return _path_is_mode_type(path, 0o100000)
49
50
51# XXX Could also expose Modules/getpath.c:isdir()
52def _path_isdir(path):
53 """Replacement for os.path.isdir."""
54 return _path_is_mode_type(path, 0o040000)
55
56
57def _path_without_ext(path, ext_type):
58 """Replacement for os.path.splitext()[0]."""
59 for suffix in suffix_list(ext_type):
60 if path.endswith(suffix):
61 return path[:-len(suffix)]
62 else:
63 raise ValueError("path is not of the specified type")
64
65
66def _path_absolute(path):
67 """Replacement for os.path.abspath."""
68 if not path:
69 path = _os.getcwd()
70 try:
71 return _os._getfullpathname(path)
72 except AttributeError:
73 if path.startswith('/'):
74 return path
75 else:
76 return _path_join(_os.getcwd(), path)
77
78
79class closing:
80
81 """Simple replacement for contextlib.closing."""
82
83 def __init__(self, obj):
84 self.obj = obj
85
86 def __enter__(self):
87 return self.obj
88
89 def __exit__(self, *args):
90 self.obj.close()
91
92
Brett Cannon51d8bfc2009-02-07 02:13:28 +000093def wrap(new, old):
94 """Simple substitute for functools.wraps."""
95 for replace in ['__module__', '__name__', '__doc__']:
96 setattr(new, replace, getattr(old, replace))
97 new.__dict__.update(old.__dict__)
98
99
Brett Cannon06c9d962009-02-07 01:52:25 +0000100def set___package__(fxn):
101 """Set __package__ on the returned module."""
102 def wrapper(*args, **kwargs):
103 module = fxn(*args, **kwargs)
104 if not hasattr(module, '__package__') or module.__package__ is None:
105 module.__package__ = module.__name__
106 if not hasattr(module, '__path__'):
107 module.__package__ = module.__package__.rpartition('.')[0]
108 return module
Brett Cannon51d8bfc2009-02-07 02:13:28 +0000109 wrap(wrapper, fxn)
Brett Cannon06c9d962009-02-07 01:52:25 +0000110 return wrapper
111
112
Brett Cannon5abdc932009-01-22 22:43:07 +0000113class BuiltinImporter:
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000114
Brett Cannon5abdc932009-01-22 22:43:07 +0000115 """Meta path loader for built-in modules.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000116
Brett Cannon5abdc932009-01-22 22:43:07 +0000117 All methods are either class or static methods, allowing direct use of the
118 class.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000119
120 """
121
Brett Cannon5abdc932009-01-22 22:43:07 +0000122 @classmethod
123 def find_module(cls, fullname, path=None):
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000124 """Try to find the built-in module.
125
126 If 'path' is ever specified then the search is considered a failure.
127
128 """
129 if path is not None:
130 return None
Brett Cannon5abdc932009-01-22 22:43:07 +0000131 return cls if imp.is_builtin(fullname) else None
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000132
Brett Cannon78246b62009-01-25 04:56:30 +0000133 @classmethod
Brett Cannon06c9d962009-02-07 01:52:25 +0000134 @set___package__
Brett Cannon78246b62009-01-25 04:56:30 +0000135 def load_module(cls, fullname):
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000136 """Load a built-in module."""
137 if fullname not in sys.builtin_module_names:
138 raise ImportError("{0} is not a built-in module".format(fullname))
Brett Cannond2e7b332009-02-17 02:45:03 +0000139 is_reload = fullname in sys.modules
140 try:
141 return imp.init_builtin(fullname)
142 except:
143 if not is_reload and fullname in sys.modules:
144 del sys.modules[fullname]
145 raise
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000146
147
Brett Cannon5abdc932009-01-22 22:43:07 +0000148class FrozenImporter:
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000149
Brett Cannon5abdc932009-01-22 22:43:07 +0000150 """Meta path class for importing frozen modules.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000151
Brett Cannon5abdc932009-01-22 22:43:07 +0000152 All methods are either class or static method to allow direct use of the
153 class.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000154
Brett Cannon5abdc932009-01-22 22:43:07 +0000155 """
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000156
Brett Cannon5abdc932009-01-22 22:43:07 +0000157 @classmethod
158 def find_module(cls, fullname, path=None):
159 """Find a frozen module."""
160 return cls if imp.is_frozen(fullname) else None
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000161
Brett Cannon5abdc932009-01-22 22:43:07 +0000162 @classmethod
Brett Cannon06c9d962009-02-07 01:52:25 +0000163 @set___package__
Brett Cannon5abdc932009-01-22 22:43:07 +0000164 def load_module(cls, fullname):
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000165 """Load a frozen module."""
Brett Cannon5abdc932009-01-22 22:43:07 +0000166 if cls.find_module(fullname) is None:
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000167 raise ImportError("{0} is not a frozen module".format(fullname))
Brett Cannond2e7b332009-02-17 02:45:03 +0000168 is_reload = fullname in sys.modules
169 try:
170 return imp.init_frozen(fullname)
171 except:
172 if not is_reload and fullname in sys.modules:
173 del sys.modules[fullname]
174 raise
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000175
176
Brett Cannon2dee5972009-02-21 03:15:37 +0000177def chained_path_hook(*path_hooks):
178 """Create a closure which sequentially checks path hooks to see which ones
179 (if any) can work with a path."""
180 def path_hook(entry):
181 """Check to see if 'entry' matches any of the enclosed path hooks."""
182 finders = []
183 for hook in path_hooks:
184 try:
185 finder = hook(entry)
186 except ImportError:
187 continue
188 else:
189 finders.append(finder)
190 if not finders:
191 raise ImportError("no finder found")
192 else:
193 return ChainedFinder(*finders)
194
195 return path_hook
196
197
198class ChainedFinder:
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000199
200 """Finder that sequentially calls other finders."""
201
Brett Cannon2dee5972009-02-21 03:15:37 +0000202 def __init__(self, *finders):
203 self._finders = finders
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000204
205 def find_module(self, fullname, path=None):
Brett Cannon2dee5972009-02-21 03:15:37 +0000206 for finder in self._finders:
207 result = finder.find_module(fullname, path)
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000208 if result:
209 return result
210 else:
211 return None
212
213
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000214def check_name(method):
215 """Decorator to verify that the module being requested matches the one the
216 loader can handle.
217
218 The first argument (self) must define _name which the second argument is
219 comapred against. If the comparison fails then ImportError is raised.
220
221 """
222 def inner(self, name, *args, **kwargs):
223 if self._name != name:
224 raise ImportError("loader cannot handle %s" % name)
225 return method(self, name, *args, **kwargs)
Brett Cannon51d8bfc2009-02-07 02:13:28 +0000226 wrap(inner, method)
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000227 return inner
228
229
Brett Cannon2dee5972009-02-21 03:15:37 +0000230class _ExtensionFileLoader:
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000231
232 """Loader for extension modules.
233
Brett Cannon2dee5972009-02-21 03:15:37 +0000234 The constructor is designed to work with FileFinder.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000235
236 """
237
238 def __init__(self, name, path, is_pkg):
239 """Initialize the loader.
240
241 If is_pkg is True then an exception is raised as extension modules
242 cannot be the __init__ module for an extension module.
243
244 """
245 self._name = name
246 self._path = path
247 if is_pkg:
248 raise ValueError("extension modules cannot be packages")
249
250 @check_name
Brett Cannon06c9d962009-02-07 01:52:25 +0000251 @set___package__
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000252 def load_module(self, fullname):
253 """Load an extension module."""
Brett Cannond2e7b332009-02-17 02:45:03 +0000254 is_reload = fullname in sys.modules
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000255 try:
256 module = imp.load_dynamic(fullname, self._path)
257 module.__loader__ = self
258 return module
259 except:
Brett Cannond2e7b332009-02-17 02:45:03 +0000260 if not is_reload and fullname in sys.modules:
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000261 del sys.modules[fullname]
262 raise
263
264 @check_name
265 def is_package(self, fullname):
266 """Return False as an extension module can never be a package."""
267 return False
268
269 @check_name
270 def get_code(self, fullname):
271 """Return None as an extension module cannot create a code object."""
272 return None
273
274 @check_name
275 def get_source(self, fullname):
276 """Return None as extension modules have no source code."""
277 return None
278
279
280def suffix_list(suffix_type):
281 """Return a list of file suffixes based on the imp file type."""
282 return [suffix[0] for suffix in imp.get_suffixes()
283 if suffix[2] == suffix_type]
284
285
Brett Cannond2e7b332009-02-17 02:45:03 +0000286def module_for_loader(fxn):
287 """Decorator to handle selecting the proper module for loaders.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000288
289 Decorated modules are passed the module to use instead of the module name.
290 The module is either from sys.modules if it already exists (for reloading)
291 or is a new module which has __name__ set. If any exception is raised by
Brett Cannond2e7b332009-02-17 02:45:03 +0000292 the decorated method and the decorator added a module to sys.modules, then
293 the module is deleted from sys.modules.
294
295 The decorator assumes that the decorated method takes self/cls as a first
296 argument and the module as the second argument.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000297
298 """
299 def decorated(self, fullname):
300 module = sys.modules.get(fullname)
301 is_reload = bool(module)
302 if not is_reload:
303 # This must be done before open() is called as the 'io' module
304 # implicitly imports 'locale' and would otherwise trigger an
305 # infinite loop.
306 module = imp.new_module(fullname)
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000307 sys.modules[fullname] = module
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000308 try:
309 return fxn(self, module)
310 except:
311 if not is_reload:
312 del sys.modules[fullname]
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000313 raise
Brett Cannon51d8bfc2009-02-07 02:13:28 +0000314 wrap(decorated, fxn)
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000315 return decorated
316
317
Brett Cannon91cf8822009-02-21 05:41:15 +0000318class PyLoader:
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000319
Brett Cannon91cf8822009-02-21 05:41:15 +0000320 """Loader base class for Python source.
321
322 Requires implementing the optional PEP 302 protocols as well as
323 source_mtime and source_path.
324
325 """
326
327 @module_for_loader
328 def load_module(self, module):
329 """Load a source module."""
330 return _load_module(module)
331
332 def _load_module(self, module):
333 """Initialize a module from source."""
334 name = module.__name__
335 source_path = self.source_path(name)
336 code_object = self.get_code(module.__name__)
337 if not hasattr(module, '__file__'):
338 module.__file__ = source_path
339 if self.is_package(name):
340 module.__path__ = [module.__file__.rsplit(path_sep, 1)[0]]
341 module.__package__ = module.__name__
342 if not hasattr(module, '__path__'):
343 module.__package__ = module.__package__.rpartition('.')[0]
344 exec(code_object, module.__dict__)
345 return module
346
347 def get_code(self, fullname):
348 """Get a code object from source."""
349 source_path = self.source_path(fullname)
350 source = self.get_data(source_path)
351 # Convert to universal newlines.
352 line_endings = b'\n'
353 for index, c in enumerate(source):
354 if c == ord(b'\n'):
355 break
356 elif c == ord(b'\r'):
357 line_endings = b'\r'
358 try:
359 if source[index+1] == ord(b'\n'):
360 line_endings += b'\n'
361 except IndexError:
362 pass
363 break
364 if line_endings != b'\n':
365 source = source.replace(line_endings, b'\n')
366 return compile(source, source_path, 'exec', dont_inherit=True)
367
368
369class PyPycLoader(PyLoader):
370
371 """Loader base class for Python source and bytecode.
372
373 Requires implementing the methods needed for PyLoader as well as
374 bytecode_path and write_bytecode.
375
376 """
377
378 @module_for_loader
379 def load_module(self, module):
380 """Load a module from source or bytecode."""
381 name = module.__name__
382 source_path = self.source_path(name)
383 bytecode_path = self.bytecode_path(name)
384 module.__file__ = source_path if source_path else bytecode_path
385 return self._load_module(module)
386
387 def get_code(self, fullname):
388 """Get a code object from source or bytecode."""
389 # XXX Care enough to make sure this call does not happen if the magic
390 # number is bad?
391 source_timestamp = self.source_mtime(fullname)
392 # Try to use bytecode if it is available.
393 bytecode_path = self.bytecode_path(fullname)
394 if bytecode_path:
395 data = self.get_data(bytecode_path)
396 magic = data[:4]
397 pyc_timestamp = marshal._r_long(data[4:8])
398 bytecode = data[8:]
399 try:
400 # Verify that the magic number is valid.
401 if imp.get_magic() != magic:
402 raise ImportError("bad magic number")
403 # Verify that the bytecode is not stale (only matters when
404 # there is source to fall back on.
405 if source_timestamp:
406 if pyc_timestamp < source_timestamp:
407 raise ImportError("bytecode is stale")
408 except ImportError:
409 # If source is available give it a shot.
410 if source_timestamp is not None:
411 pass
412 else:
413 raise
414 else:
415 # Bytecode seems fine, so try to use it.
416 # XXX If the bytecode is ill-formed, would it be beneficial to
417 # try for using source if available and issue a warning?
418 return marshal.loads(bytecode)
419 elif source_timestamp is None:
420 raise ImportError("no source or bytecode available to create code "
421 "object for {0!r}".format(fullname))
422 # Use the source.
423 code_object = super().get_code(fullname)
424 # Generate bytecode and write it out.
425 if not sys.dont_write_bytecode:
426 data = bytearray(imp.get_magic())
427 data.extend(marshal._w_long(source_timestamp))
428 data.extend(marshal.dumps(code_object))
429 self.write_bytecode(fullname, data)
430 return code_object
431
432
433class PyFileLoader(PyLoader):
434
435 """Load a Python source file."""
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000436
437 def __init__(self, name, path, is_pkg):
438 self._name = name
439 self._is_pkg = is_pkg
440 # Figure out the base path based on whether it was source or bytecode
441 # that was found.
442 try:
443 self._base_path = _path_without_ext(path, imp.PY_SOURCE)
444 except ValueError:
445 self._base_path = _path_without_ext(path, imp.PY_COMPILED)
446
447 def _find_path(self, ext_type):
448 """Find a path from the base path and the specified extension type that
449 exists, returning None if one is not found."""
450 for suffix in suffix_list(ext_type):
451 path = self._base_path + suffix
452 if _path_exists(path):
453 return path
454 else:
455 return None
456
Brett Cannon51c50262009-02-01 05:33:17 +0000457 @check_name
458 def source_path(self, fullname):
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000459 """Return the path to an existing source file for the module, or None
460 if one cannot be found."""
461 # Not a property so that it is easy to override.
462 return self._find_path(imp.PY_SOURCE)
463
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000464
465 @check_name
466 def source_mtime(self, name):
467 """Return the modification time of the source for the specified
468 module."""
Brett Cannon51c50262009-02-01 05:33:17 +0000469 source_path = self.source_path(name)
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000470 if not source_path:
471 return None
472 return int(_os.stat(source_path).st_mtime)
473
474 @check_name
475 def get_source(self, fullname):
476 """Return the source for the module as a string.
477
478 Return None if the source is not available. Raise ImportError if the
479 laoder cannot handle the specified module.
480
481 """
Brett Cannon51c50262009-02-01 05:33:17 +0000482 source_path = self._source_path(name)
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000483 if source_path is None:
484 return None
485 import tokenize
Brett Cannonb4a1b8c2009-01-19 06:56:16 +0000486 with closing(_fileio._FileIO(source_path, 'r')) as file:
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000487 encoding, lines = tokenize.detect_encoding(file.readline)
488 # XXX Will fail when passed to compile() if the encoding is
489 # anything other than UTF-8.
490 return open(source_path, encoding=encoding).read()
491
Brett Cannon91cf8822009-02-21 05:41:15 +0000492
493 def get_data(self, path):
494 """Return the data from path as raw bytes."""
495 return _fileio._FileIO(path, 'r').read()
496
497 @check_name
498 def is_package(self, fullname):
499 """Return a boolean based on whether the module is a package.
500
501 Raises ImportError (like get_source) if the loader cannot handle the
502 package.
503
504 """
505 return self._is_pkg
506
507
508# XXX Rename _PyFileLoader throughout
509class PyPycFileLoader(PyPycLoader, PyFileLoader):
510
511 """Load a module from a source or bytecode file."""
512
513 @check_name
514 def bytecode_path(self, fullname):
515 """Return the path to a bytecode file, or None if one does not
516 exist."""
517 # Not a property for easy overriding.
518 return self._find_path(imp.PY_COMPILED)
519
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000520 @check_name
Brett Cannon776e7012009-02-01 06:07:57 +0000521 def write_bytecode(self, name, data):
522 """Write out 'data' for the specified module, returning a boolean
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000523 signifying if the write-out actually occurred.
524
525 Raises ImportError (just like get_source) if the specified module
526 cannot be handled by the loader.
527
528 """
Brett Cannon51c50262009-02-01 05:33:17 +0000529 bytecode_path = self.bytecode_path(name)
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000530 if not bytecode_path:
531 bytecode_path = self._base_path + suffix_list(imp.PY_COMPILED)[0]
532 file = _fileio._FileIO(bytecode_path, 'w')
533 try:
534 with closing(file) as bytecode_file:
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000535 bytecode_file.write(data)
536 return True
537 except IOError as exc:
538 if exc.errno == errno.EACCES:
539 return False
540 else:
541 raise
542
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000543
Brett Cannon2dee5972009-02-21 03:15:37 +0000544class FileFinder:
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000545
Brett Cannon2dee5972009-02-21 03:15:37 +0000546 """Base class for file finders.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000547
548 Subclasses are expected to define the following attributes:
549
550 * _suffixes
551 Sequence of file suffixes whose order will be followed.
552
553 * _possible_package
554 True if importer should check for packages.
555
556 * _loader
557 A callable that takes the module name, a file path, and whether
558 the path points to a package and returns a loader for the module
559 found at that path.
560
561 """
562
563 def __init__(self, path_entry):
564 """Initialize an importer for the passed-in sys.path entry (which is
565 assumed to have already been verified as an existing directory).
566
567 Can be used as an entry on sys.path_hook.
568
569 """
Brett Cannon2dee5972009-02-21 03:15:37 +0000570 absolute_path = _path_absolute(path_entry)
571 if not _path_isdir(absolute_path):
572 raise ImportError("only directories are supported")
573 self._path_entry = absolute_path
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000574
575 def find_module(self, fullname, path=None):
Brett Cannon2dee5972009-02-21 03:15:37 +0000576 tail_module = fullname.rpartition('.')[2]
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000577 package_directory = None
578 if self._possible_package:
579 for ext in self._suffixes:
580 package_directory = _path_join(self._path_entry, tail_module)
581 init_filename = '__init__' + ext
582 package_init = _path_join(package_directory, init_filename)
583 if (_path_isfile(package_init) and
584 _case_ok(self._path_entry, tail_module) and
585 _case_ok(package_directory, init_filename)):
586 return self._loader(fullname, package_init, True)
587 for ext in self._suffixes:
588 file_name = tail_module + ext
589 file_path = _path_join(self._path_entry, file_name)
590 if (_path_isfile(file_path) and
591 _case_ok(self._path_entry, file_name)):
592 return self._loader(fullname, file_path, False)
593 else:
594 # Raise a warning if it matches a directory w/o an __init__ file.
595 if (package_directory is not None and
596 _path_isdir(package_directory) and
597 _case_ok(self._path_entry, tail_module)):
598 _warnings.warn("Not importing directory %s: missing __init__"
599 % package_directory, ImportWarning)
600 return None
601
602
Brett Cannon2dee5972009-02-21 03:15:37 +0000603class ExtensionFileFinder(FileFinder):
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000604
605 """Importer for extension files."""
606
607 _possible_package = False
608 _loader = _ExtensionFileLoader
609
610 def __init__(self, path_entry):
611 # Assigning to _suffixes here instead of at the class level because
612 # imp is not imported at the time of class creation.
613 self._suffixes = suffix_list(imp.C_EXTENSION)
Brett Cannon2dee5972009-02-21 03:15:37 +0000614 super().__init__(path_entry)
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000615
616
Brett Cannon2dee5972009-02-21 03:15:37 +0000617class PyFileFinder(FileFinder):
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000618
619 """Importer for source/bytecode files."""
620
621 _possible_package = True
Brett Cannon91cf8822009-02-21 05:41:15 +0000622 _loader = PyFileLoader
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000623
624 def __init__(self, path_entry):
625 # Lack of imp during class creation means _suffixes is set here.
626 # Make sure that Python source files are listed first! Needed for an
627 # optimization by the loader.
628 self._suffixes = suffix_list(imp.PY_SOURCE)
Brett Cannon2dee5972009-02-21 03:15:37 +0000629 super().__init__(path_entry)
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000630
631
Brett Cannon4afab6b2009-02-21 03:31:35 +0000632class PyPycFileFinder(PyFileFinder):
633
634 """Finder for source and bytecode files."""
635
Brett Cannon91cf8822009-02-21 05:41:15 +0000636 _loader = PyPycFileLoader
637
Brett Cannon4afab6b2009-02-21 03:31:35 +0000638 def __init__(self, path_entry):
639 super().__init__(path_entry)
640 self._suffixes += suffix_list(imp.PY_COMPILED)
641
642
Brett Cannonf7e5a8c2009-02-05 02:52:18 +0000643class PathFinder:
Brett Cannon1d376682009-02-02 19:19:36 +0000644
645 """Meta path finder for sys.(path|path_hooks|path_importer_cache)."""
646
Brett Cannonf7e5a8c2009-02-05 02:52:18 +0000647 @classmethod
Brett Cannon32732e32009-02-15 05:48:13 +0000648 def _path_hooks(cls, path, hooks=None):
649 """Search sequence of hooks for a finder for 'path'.
Brett Cannon1d376682009-02-02 19:19:36 +0000650
Brett Cannon32732e32009-02-15 05:48:13 +0000651 If 'hooks' is false then use sys.path_hooks.
Brett Cannon1d376682009-02-02 19:19:36 +0000652
653 """
Brett Cannon32732e32009-02-15 05:48:13 +0000654 if not hooks:
655 hooks = sys.path_hooks
656 for hook in hooks:
Brett Cannon1d376682009-02-02 19:19:36 +0000657 try:
658 return hook(path)
659 except ImportError:
660 continue
661 else:
Brett Cannon32732e32009-02-15 05:48:13 +0000662 raise ImportError("no path hook found for {0}".format(path))
Brett Cannon1d376682009-02-02 19:19:36 +0000663
Brett Cannonf7e5a8c2009-02-05 02:52:18 +0000664 @classmethod
Brett Cannon32732e32009-02-15 05:48:13 +0000665 def _path_importer_cache(cls, path, default=None):
Brett Cannon1d376682009-02-02 19:19:36 +0000666 """Get the finder for the path from sys.path_importer_cache.
667
668 If the path is not in the cache, find the appropriate finder and cache
669 it. If None is cached, get the default finder and cache that
670 (if applicable).
671
672 Because of NullImporter, some finder should be returned. The only
673 explicit fail case is if None is cached but the path cannot be used for
674 the default hook, for which ImportError is raised.
675
676 """
677 try:
Brett Cannonf7e5a8c2009-02-05 02:52:18 +0000678 finder = sys.path_importer_cache[path]
Brett Cannon1d376682009-02-02 19:19:36 +0000679 except KeyError:
Brett Cannonf7e5a8c2009-02-05 02:52:18 +0000680 finder = cls._path_hooks(path)
Brett Cannon1d376682009-02-02 19:19:36 +0000681 sys.path_importer_cache[path] = finder
682 else:
Brett Cannon32732e32009-02-15 05:48:13 +0000683 if finder is None and default:
Brett Cannon1d376682009-02-02 19:19:36 +0000684 # Raises ImportError on failure.
Brett Cannon32732e32009-02-15 05:48:13 +0000685 finder = default(path)
Brett Cannon1d376682009-02-02 19:19:36 +0000686 sys.path_importer_cache[path] = finder
687 return finder
688
Brett Cannonf7e5a8c2009-02-05 02:52:18 +0000689 @classmethod
690 def find_module(cls, fullname, path=None):
Brett Cannon1d376682009-02-02 19:19:36 +0000691 """Find the module on sys.path or 'path'."""
692 if not path:
693 path = sys.path
694 for entry in path:
695 try:
Brett Cannonf7e5a8c2009-02-05 02:52:18 +0000696 finder = cls._path_importer_cache(entry)
Brett Cannon1d376682009-02-02 19:19:36 +0000697 except ImportError:
698 continue
699 loader = finder.find_module(fullname)
700 if loader:
701 return loader
702 else:
703 return None
704
705
Brett Cannon4afab6b2009-02-21 03:31:35 +0000706_DEFAULT_PATH_HOOK = chained_path_hook(ExtensionFileFinder, PyPycFileFinder)
Brett Cannon2dee5972009-02-21 03:15:37 +0000707
Brett Cannon32732e32009-02-15 05:48:13 +0000708class _DefaultPathFinder(PathFinder):
709
710 """Subclass of PathFinder that implements implicit semantics for
711 __import__."""
712
Brett Cannon32732e32009-02-15 05:48:13 +0000713 @classmethod
714 def _path_hooks(cls, path):
715 """Search sys.path_hooks as well as implicit path hooks."""
716 try:
717 return super()._path_hooks(path)
718 except ImportError:
Brett Cannon2dee5972009-02-21 03:15:37 +0000719 implicit_hooks = [_DEFAULT_PATH_HOOK, imp.NullImporter]
Brett Cannon32732e32009-02-15 05:48:13 +0000720 return super()._path_hooks(path, implicit_hooks)
721
722 @classmethod
723 def _path_importer_cache(cls, path):
724 """Use the default path hook when None is stored in
725 sys.path_importer_cache."""
Brett Cannon2dee5972009-02-21 03:15:37 +0000726 return super()._path_importer_cache(path, _DEFAULT_PATH_HOOK)
Brett Cannon32732e32009-02-15 05:48:13 +0000727
728
Brett Cannon2dee5972009-02-21 03:15:37 +0000729class ImportLockContext:
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000730
731 """Context manager for the import lock."""
732
733 def __enter__(self):
734 """Acquire the import lock."""
735 imp.acquire_lock()
736
737 def __exit__(self, exc_type, exc_value, exc_traceback):
738 """Release the import lock regardless of any raised exceptions."""
739 imp.release_lock()
740
741
Brett Cannon32732e32009-02-15 05:48:13 +0000742_IMPLICIT_META_PATH = [BuiltinImporter, FrozenImporter, _DefaultPathFinder]
743
Brett Cannon7f9876c2009-02-06 02:47:33 +0000744def _gcd_import(name, package=None, level=0):
745 """Import and return the module based on its name, the package the call is
746 being made from, and the level adjustment.
747
748 This function represents the greatest common denominator of functionality
Brett Cannon2c318a12009-02-07 01:15:27 +0000749 between import_module and __import__. This includes settting __package__ if
750 the loader did not.
751
Brett Cannon7f9876c2009-02-06 02:47:33 +0000752 """
Brett Cannon2c318a12009-02-07 01:15:27 +0000753 if package:
754 if not hasattr(package, 'rindex'):
755 raise ValueError("__package__ not set to a string")
756 elif package not in sys.modules:
757 msg = ("Parent module {0!r} not loaded, cannot perform relative "
758 "import")
759 raise SystemError(msg.format(package))
760 if not name and level == 0:
761 raise ValueError("Empty module name")
Brett Cannon7f9876c2009-02-06 02:47:33 +0000762 if level > 0:
Brett Cannon2c318a12009-02-07 01:15:27 +0000763 dot = len(package)
Brett Cannon7f9876c2009-02-06 02:47:33 +0000764 for x in range(level, 1, -1):
765 try:
766 dot = package.rindex('.', 0, dot)
Brett Cannon7f9876c2009-02-06 02:47:33 +0000767 except ValueError:
Brett Cannon2c318a12009-02-07 01:15:27 +0000768 raise ValueError("attempted relative import beyond "
769 "top-level package")
770 if name:
771 name = "{0}.{1}".format(package[:dot], name)
772 else:
773 name = package[:dot]
Brett Cannon7f9876c2009-02-06 02:47:33 +0000774 with ImportLockContext():
775 try:
776 return sys.modules[name]
777 except KeyError:
778 pass
779 parent = name.rpartition('.')[0]
780 path = None
781 if parent:
782 if parent not in sys.modules:
Brett Cannon2c318a12009-02-07 01:15:27 +0000783 _gcd_import(parent)
784 # Backwards-compatibility; be nicer to skip the dict lookup.
785 parent_module = sys.modules[parent]
Brett Cannon7f9876c2009-02-06 02:47:33 +0000786 path = parent_module.__path__
Brett Cannon32732e32009-02-15 05:48:13 +0000787 meta_path = sys.meta_path + _IMPLICIT_META_PATH
Brett Cannon2c318a12009-02-07 01:15:27 +0000788 for finder in meta_path:
Brett Cannon7f9876c2009-02-06 02:47:33 +0000789 loader = finder.find_module(name, path)
Brett Cannon2c318a12009-02-07 01:15:27 +0000790 if loader is not None:
791 loader.load_module(name)
792 break
Brett Cannon7f9876c2009-02-06 02:47:33 +0000793 else:
794 raise ImportError("No module named {0}".format(name))
Brett Cannon2c318a12009-02-07 01:15:27 +0000795 # Backwards-compatibility; be nicer to skip the dict lookup.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000796 module = sys.modules[name]
797 if parent:
Brett Cannon2c318a12009-02-07 01:15:27 +0000798 # Set the module as an attribute on its parent.
799 setattr(parent_module, name.rpartition('.')[2], module)
800 # Set __package__ if the loader did not.
801 if not hasattr(module, '__package__') or module.__package__ is None:
802 # Watch out for what comes out of sys.modules to not be a module,
803 # e.g. an int.
804 try:
805 module.__package__ = module.__name__
806 if not hasattr(module, '__path__'):
807 module.__package__ = module.__package__.rpartition('.')[0]
808 except AttributeError:
809 pass
810 return module
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000811
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000812
Brett Cannon2c318a12009-02-07 01:15:27 +0000813def _import(name, globals={}, locals={}, fromlist=[], level=0):
814 """Import a module.
815
816 The 'globals' argument is used to infer where the import is occuring from
817 to handle relative imports. The 'locals' argument is ignored. The
818 'fromlist' argument specifies what should exist as attributes on the module
819 being imported (e.g. ``from module import <fromlist>``). The 'level'
820 argument represents the package location to import from in a relative
821 import (e.g. ``from ..pkg import mod`` would have a 'level' of 2).
822
823 """
824 if level == 0:
825 module = _gcd_import(name)
826 else:
827 # __package__ is not guaranteed to be defined.
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000828 try:
Brett Cannon2c318a12009-02-07 01:15:27 +0000829 package = globals['__package__']
830 except KeyError:
831 package = globals['__name__']
832 if '__path__' not in globals:
833 package = package.rpartition('.')[0]
834 module = _gcd_import(name, package, level)
835 # The hell that is fromlist ...
836 if not fromlist:
837 # Return up to the first dot in 'name'. This is complicated by the fact
838 # that 'name' may be relative.
839 if level == 0:
840 return sys.modules[name.partition('.')[0]]
841 elif not name:
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000842 return module
Brett Cannon2c318a12009-02-07 01:15:27 +0000843 else:
844 cut_off = len(name) - len(name.partition('.')[0])
845 return sys.modules[module.__name__[:-cut_off]]
846 else:
847 # If a package was imported, try to import stuff from fromlist.
848 if hasattr(module, '__path__'):
849 if '*' in fromlist and hasattr(module, '__all__'):
850 fromlist.remove('*')
851 fromlist.extend(module.__all__)
852 for x in (y for y in fromlist if not hasattr(module,y)):
853 try:
854 _gcd_import('{0}.{1}'.format(module.__name__, x))
855 except ImportError:
856 pass
857 return module
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000858
Brett Cannon23cbd8a2009-01-18 00:24:28 +0000859
860# XXX Eventually replace with a proper __all__ value (i.e., don't expose os
861# replacements but do expose _ExtensionFileLoader, etc. for testing).
862__all__ = [obj for obj in globals().keys() if not obj.startswith('__')]