blob: 3508ce96b02337ac4fc996bc6eb0d31b463de9b9 [file] [log] [blame]
Eric Snow32439d62015-05-02 19:15:18 -06001"""Core implementation of path-based 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# IMPORTANT: Whenever making changes to this module, be sure to run
11# a top-level make in order to get the frozen version of the module
12# updated. Not doing so will result in the Makefile to fail for
13# all others who don't have a ./python around to freeze the module
14# in the early stages of compilation.
15#
16
17# See importlib._setup() for what is injected into the global namespace.
18
19# When editing this code be aware that code executed at import time CANNOT
20# reference any injected objects! This includes not only global code but also
21# anything specified at the class level.
22
23# Bootstrap-related code ######################################################
24
25_CASE_INSENSITIVE_PLATFORMS = 'win', 'cygwin', 'darwin'
26
27
28def _make_relax_case():
29 if sys.platform.startswith(_CASE_INSENSITIVE_PLATFORMS):
30 def _relax_case():
31 """True if filenames must be checked case-insensitively."""
32 return b'PYTHONCASEOK' in _os.environ
33 else:
34 def _relax_case():
35 """True if filenames must be checked case-insensitively."""
36 return False
37 return _relax_case
38
39
40def _w_long(x):
41 """Convert a 32-bit integer to little-endian."""
42 return (int(x) & 0xFFFFFFFF).to_bytes(4, 'little')
43
44
45def _r_long(int_bytes):
46 """Convert 4 bytes in little-endian to an integer."""
47 return int.from_bytes(int_bytes, 'little')
48
49
50def _path_join(*path_parts):
51 """Replacement for os.path.join()."""
52 return path_sep.join([part.rstrip(path_separators)
53 for part in path_parts if part])
54
55
56def _path_split(path):
57 """Replacement for os.path.split()."""
58 if len(path_separators) == 1:
59 front, _, tail = path.rpartition(path_sep)
60 return front, tail
61 for x in reversed(path):
62 if x in path_separators:
63 front, tail = path.rsplit(x, maxsplit=1)
64 return front, tail
65 return '', path
66
67
68def _path_stat(path):
69 """Stat the path.
70
71 Made a separate function to make it easier to override in experiments
72 (e.g. cache stat results).
73
74 """
75 return _os.stat(path)
76
77
78def _path_is_mode_type(path, mode):
79 """Test whether the path is the specified mode type."""
80 try:
81 stat_info = _path_stat(path)
82 except OSError:
83 return False
84 return (stat_info.st_mode & 0o170000) == mode
85
86
87def _path_isfile(path):
88 """Replacement for os.path.isfile."""
89 return _path_is_mode_type(path, 0o100000)
90
91
92def _path_isdir(path):
93 """Replacement for os.path.isdir."""
94 if not path:
95 path = _os.getcwd()
96 return _path_is_mode_type(path, 0o040000)
97
98
99def _write_atomic(path, data, mode=0o666):
100 """Best-effort function to write data to a path atomically.
101 Be prepared to handle a FileExistsError if concurrent writing of the
102 temporary file is attempted."""
103 # id() is used to generate a pseudo-random filename.
104 path_tmp = '{}.{}'.format(path, id(path))
105 fd = _os.open(path_tmp,
106 _os.O_EXCL | _os.O_CREAT | _os.O_WRONLY, mode & 0o666)
107 try:
108 # We first write data to a temporary file, and then use os.replace() to
109 # perform an atomic rename.
110 with _io.FileIO(fd, 'wb') as file:
111 file.write(data)
112 _os.replace(path_tmp, path)
113 except OSError:
114 try:
115 _os.unlink(path_tmp)
116 except OSError:
117 pass
118 raise
119
120
121_code_type = type(_write_atomic.__code__)
122
123
124# Finder/loader utility code ###############################################
125
126# Magic word to reject .pyc files generated by other Python versions.
127# It should change for each incompatible change to the bytecode.
128#
129# The value of CR and LF is incorporated so if you ever read or write
130# a .pyc file in text mode the magic number will be wrong; also, the
131# Apple MPW compiler swaps their values, botching string constants.
132#
133# The magic numbers must be spaced apart at least 2 values, as the
134# -U interpeter flag will cause MAGIC+1 being used. They have been
135# odd numbers for some time now.
136#
137# There were a variety of old schemes for setting the magic number.
138# The current working scheme is to increment the previous value by
139# 10.
140#
141# Starting with the adoption of PEP 3147 in Python 3.2, every bump in magic
142# number also includes a new "magic tag", i.e. a human readable string used
143# to represent the magic number in __pycache__ directories. When you change
144# the magic number, you must also set a new unique magic tag. Generally this
145# can be named after the Python major version of the magic number bump, but
146# it can really be anything, as long as it's different than anything else
147# that's come before. The tags are included in the following table, starting
148# with Python 3.2a0.
149#
150# Known values:
151# Python 1.5: 20121
152# Python 1.5.1: 20121
153# Python 1.5.2: 20121
154# Python 1.6: 50428
155# Python 2.0: 50823
156# Python 2.0.1: 50823
157# Python 2.1: 60202
158# Python 2.1.1: 60202
159# Python 2.1.2: 60202
160# Python 2.2: 60717
161# Python 2.3a0: 62011
162# Python 2.3a0: 62021
163# Python 2.3a0: 62011 (!)
164# Python 2.4a0: 62041
165# Python 2.4a3: 62051
166# Python 2.4b1: 62061
167# Python 2.5a0: 62071
168# Python 2.5a0: 62081 (ast-branch)
169# Python 2.5a0: 62091 (with)
170# Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
171# Python 2.5b3: 62101 (fix wrong code: for x, in ...)
172# Python 2.5b3: 62111 (fix wrong code: x += yield)
173# Python 2.5c1: 62121 (fix wrong lnotab with for loops and
174# storing constants that should have been removed)
175# Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
176# Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode)
177# Python 2.6a1: 62161 (WITH_CLEANUP optimization)
178# Python 2.7a0: 62171 (optimize list comprehensions/change LIST_APPEND)
179# Python 2.7a0: 62181 (optimize conditional branches:
180# introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE)
181# Python 2.7a0 62191 (introduce SETUP_WITH)
182# Python 2.7a0 62201 (introduce BUILD_SET)
183# Python 2.7a0 62211 (introduce MAP_ADD and SET_ADD)
184# Python 3000: 3000
185# 3010 (removed UNARY_CONVERT)
186# 3020 (added BUILD_SET)
187# 3030 (added keyword-only parameters)
188# 3040 (added signature annotations)
189# 3050 (print becomes a function)
190# 3060 (PEP 3115 metaclass syntax)
191# 3061 (string literals become unicode)
192# 3071 (PEP 3109 raise changes)
193# 3081 (PEP 3137 make __file__ and __name__ unicode)
194# 3091 (kill str8 interning)
195# 3101 (merge from 2.6a0, see 62151)
196# 3103 (__file__ points to source file)
197# Python 3.0a4: 3111 (WITH_CLEANUP optimization).
198# Python 3.0a5: 3131 (lexical exception stacking, including POP_EXCEPT)
199# Python 3.1a0: 3141 (optimize list, set and dict comprehensions:
200# change LIST_APPEND and SET_ADD, add MAP_ADD)
201# Python 3.1a0: 3151 (optimize conditional branches:
202# introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE)
203# Python 3.2a0: 3160 (add SETUP_WITH)
204# tag: cpython-32
205# Python 3.2a1: 3170 (add DUP_TOP_TWO, remove DUP_TOPX and ROT_FOUR)
206# tag: cpython-32
207# Python 3.2a2 3180 (add DELETE_DEREF)
208# Python 3.3a0 3190 __class__ super closure changed
209# Python 3.3a0 3200 (__qualname__ added)
210# 3210 (added size modulo 2**32 to the pyc header)
211# Python 3.3a1 3220 (changed PEP 380 implementation)
212# Python 3.3a4 3230 (revert changes to implicit __class__ closure)
213# Python 3.4a1 3250 (evaluate positional default arguments before
214# keyword-only defaults)
215# Python 3.4a1 3260 (add LOAD_CLASSDEREF; allow locals of class to override
216# free vars)
217# Python 3.4a1 3270 (various tweaks to the __class__ closure)
218# Python 3.4a1 3280 (remove implicit class argument)
219# Python 3.4a4 3290 (changes to __qualname__ computation)
220# Python 3.4a4 3300 (more changes to __qualname__ computation)
221# Python 3.4rc2 3310 (alter __qualname__ computation)
222# Python 3.5a0 3320 (matrix multiplication operator)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400223# Python 3.5b1 3330 (PEP 448: Additional Unpacking Generalizations)
Benjamin Petersonee853392015-05-28 14:30:26 -0500224# Python 3.5b2 3340 (fix dictionary display evaluation order #11205)
Yury Selivanov5376ba92015-06-22 12:19:30 -0400225# Python 3.5b2 3350 (add GET_YIELD_FROM_ITER opcode #24400)
Eric Snow32439d62015-05-02 19:15:18 -0600226#
227# MAGIC must change whenever the bytecode emitted by the compiler may no
228# longer be understood by older implementations of the eval loop (usually
229# due to the addition of new opcodes).
230
Yury Selivanov5376ba92015-06-22 12:19:30 -0400231MAGIC_NUMBER = (3350).to_bytes(2, 'little') + b'\r\n'
Eric Snow32439d62015-05-02 19:15:18 -0600232_RAW_MAGIC_NUMBER = int.from_bytes(MAGIC_NUMBER, 'little') # For import.c
233
234_PYCACHE = '__pycache__'
235_OPT = 'opt-'
236
237SOURCE_SUFFIXES = ['.py'] # _setup() adds .pyw as needed.
238
239BYTECODE_SUFFIXES = ['.pyc']
240# Deprecated.
241DEBUG_BYTECODE_SUFFIXES = OPTIMIZED_BYTECODE_SUFFIXES = BYTECODE_SUFFIXES
242
243def cache_from_source(path, debug_override=None, *, optimization=None):
244 """Given the path to a .py file, return the path to its .pyc file.
245
246 The .py file does not need to exist; this simply returns the path to the
247 .pyc file calculated as if the .py file were imported.
248
249 The 'optimization' parameter controls the presumed optimization level of
250 the bytecode file. If 'optimization' is not None, the string representation
251 of the argument is taken and verified to be alphanumeric (else ValueError
252 is raised).
253
254 The debug_override parameter is deprecated. If debug_override is not None,
255 a True value is the same as setting 'optimization' to the empty string
256 while a False value is equivalent to setting 'optimization' to '1'.
257
258 If sys.implementation.cache_tag is None then NotImplementedError is raised.
259
260 """
261 if debug_override is not None:
262 _warnings.warn('the debug_override parameter is deprecated; use '
263 "'optimization' instead", DeprecationWarning)
264 if optimization is not None:
265 message = 'debug_override or optimization must be set to None'
266 raise TypeError(message)
267 optimization = '' if debug_override else 1
268 head, tail = _path_split(path)
269 base, sep, rest = tail.rpartition('.')
270 tag = sys.implementation.cache_tag
271 if tag is None:
272 raise NotImplementedError('sys.implementation.cache_tag is None')
273 almost_filename = ''.join([(base if base else rest), sep, tag])
274 if optimization is None:
275 if sys.flags.optimize == 0:
276 optimization = ''
277 else:
278 optimization = sys.flags.optimize
279 optimization = str(optimization)
280 if optimization != '':
281 if not optimization.isalnum():
282 raise ValueError('{!r} is not alphanumeric'.format(optimization))
283 almost_filename = '{}.{}{}'.format(almost_filename, _OPT, optimization)
284 return _path_join(head, _PYCACHE, almost_filename + BYTECODE_SUFFIXES[0])
285
286
287def source_from_cache(path):
288 """Given the path to a .pyc. file, return the path to its .py file.
289
290 The .pyc file does not need to exist; this simply returns the path to
291 the .py file calculated to correspond to the .pyc file. If path does
292 not conform to PEP 3147/488 format, ValueError will be raised. If
293 sys.implementation.cache_tag is None then NotImplementedError is raised.
294
295 """
296 if sys.implementation.cache_tag is None:
297 raise NotImplementedError('sys.implementation.cache_tag is None')
298 head, pycache_filename = _path_split(path)
299 head, pycache = _path_split(head)
300 if pycache != _PYCACHE:
301 raise ValueError('{} not bottom-level directory in '
302 '{!r}'.format(_PYCACHE, path))
303 dot_count = pycache_filename.count('.')
304 if dot_count not in {2, 3}:
305 raise ValueError('expected only 2 or 3 dots in '
306 '{!r}'.format(pycache_filename))
307 elif dot_count == 3:
308 optimization = pycache_filename.rsplit('.', 2)[-2]
309 if not optimization.startswith(_OPT):
310 raise ValueError("optimization portion of filename does not start "
311 "with {!r}".format(_OPT))
312 opt_level = optimization[len(_OPT):]
313 if not opt_level.isalnum():
314 raise ValueError("optimization level {!r} is not an alphanumeric "
315 "value".format(optimization))
316 base_filename = pycache_filename.partition('.')[0]
317 return _path_join(head, base_filename + SOURCE_SUFFIXES[0])
318
319
320def _get_sourcefile(bytecode_path):
321 """Convert a bytecode file path to a source path (if possible).
322
323 This function exists purely for backwards-compatibility for
324 PyImport_ExecCodeModuleWithFilenames() in the C API.
325
326 """
327 if len(bytecode_path) == 0:
328 return None
329 rest, _, extension = bytecode_path.rpartition('.')
330 if not rest or extension.lower()[-3:-1] != 'py':
331 return bytecode_path
332 try:
333 source_path = source_from_cache(bytecode_path)
334 except (NotImplementedError, ValueError):
335 source_path = bytecode_path[:-1]
336 return source_path if _path_isfile(source_path) else bytecode_path
337
338
339def _get_cached(filename):
340 if filename.endswith(tuple(SOURCE_SUFFIXES)):
341 try:
342 return cache_from_source(filename)
343 except NotImplementedError:
344 pass
345 elif filename.endswith(tuple(BYTECODE_SUFFIXES)):
346 return filename
347 else:
348 return None
349
350
351def _calc_mode(path):
352 """Calculate the mode permissions for a bytecode file."""
353 try:
354 mode = _path_stat(path).st_mode
355 except OSError:
356 mode = 0o666
357 # We always ensure write access so we can update cached files
358 # later even when the source files are read-only on Windows (#6074)
359 mode |= 0o200
360 return mode
361
362
363def _verbose_message(message, *args, verbosity=1):
364 """Print the message to stderr if -v/PYTHONVERBOSE is turned on."""
365 if sys.flags.verbose >= verbosity:
366 if not message.startswith(('#', 'import ')):
367 message = '# ' + message
368 print(message.format(*args), file=sys.stderr)
369
370
371def _check_name(method):
372 """Decorator to verify that the module being requested matches the one the
373 loader can handle.
374
375 The first argument (self) must define _name which the second argument is
376 compared against. If the comparison fails then ImportError is raised.
377
378 """
379 def _check_name_wrapper(self, name=None, *args, **kwargs):
380 if name is None:
381 name = self.name
382 elif self.name != name:
Nick Coghland5cacbb2015-05-23 22:24:10 +1000383 raise ImportError('loader for %s cannot handle %s' %
384 (self.name, name), name=name)
Eric Snow32439d62015-05-02 19:15:18 -0600385 return method(self, name, *args, **kwargs)
386 try:
387 _wrap = _bootstrap._wrap
388 except NameError:
389 # XXX yuck
390 def _wrap(new, old):
391 for replace in ['__module__', '__name__', '__qualname__', '__doc__']:
392 if hasattr(old, replace):
393 setattr(new, replace, getattr(old, replace))
394 new.__dict__.update(old.__dict__)
395 _wrap(_check_name_wrapper, method)
396 return _check_name_wrapper
397
398
399def _find_module_shim(self, fullname):
400 """Try to find a loader for the specified module by delegating to
401 self.find_loader().
402
403 This method is deprecated in favor of finder.find_spec().
404
405 """
406 # Call find_loader(). If it returns a string (indicating this
407 # is a namespace package portion), generate a warning and
408 # return None.
409 loader, portions = self.find_loader(fullname)
410 if loader is None and len(portions):
411 msg = 'Not importing directory {}: missing __init__'
412 _warnings.warn(msg.format(portions[0]), ImportWarning)
413 return loader
414
415
Eric Snow32439d62015-05-02 19:15:18 -0600416def _validate_bytecode_header(data, source_stats=None, name=None, path=None):
417 """Validate the header of the passed-in bytecode against source_stats (if
418 given) and returning the bytecode that can be compiled by compile().
419
420 All other arguments are used to enhance error reporting.
421
422 ImportError is raised when the magic number is incorrect or the bytecode is
423 found to be stale. EOFError is raised when the data is found to be
424 truncated.
425
426 """
427 exc_details = {}
428 if name is not None:
429 exc_details['name'] = name
430 else:
431 # To prevent having to make all messages have a conditional name.
432 name = '<bytecode>'
433 if path is not None:
434 exc_details['path'] = path
435 magic = data[:4]
436 raw_timestamp = data[4:8]
437 raw_size = data[8:12]
438 if magic != MAGIC_NUMBER:
439 message = 'bad magic number in {!r}: {!r}'.format(name, magic)
440 _verbose_message(message)
441 raise ImportError(message, **exc_details)
442 elif len(raw_timestamp) != 4:
443 message = 'reached EOF while reading timestamp in {!r}'.format(name)
444 _verbose_message(message)
445 raise EOFError(message)
446 elif len(raw_size) != 4:
447 message = 'reached EOF while reading size of source in {!r}'.format(name)
448 _verbose_message(message)
449 raise EOFError(message)
450 if source_stats is not None:
451 try:
452 source_mtime = int(source_stats['mtime'])
453 except KeyError:
454 pass
455 else:
456 if _r_long(raw_timestamp) != source_mtime:
457 message = 'bytecode is stale for {!r}'.format(name)
458 _verbose_message(message)
459 raise ImportError(message, **exc_details)
460 try:
461 source_size = source_stats['size'] & 0xFFFFFFFF
462 except KeyError:
463 pass
464 else:
465 if _r_long(raw_size) != source_size:
466 raise ImportError('bytecode is stale for {!r}'.format(name),
467 **exc_details)
468 return data[12:]
469
470
471def _compile_bytecode(data, name=None, bytecode_path=None, source_path=None):
472 """Compile bytecode as returned by _validate_bytecode_header()."""
473 code = marshal.loads(data)
474 if isinstance(code, _code_type):
475 _verbose_message('code object from {!r}', bytecode_path)
476 if source_path is not None:
477 _imp._fix_co_filename(code, source_path)
478 return code
479 else:
480 raise ImportError('Non-code object in {!r}'.format(bytecode_path),
481 name=name, path=bytecode_path)
482
483def _code_to_bytecode(code, mtime=0, source_size=0):
484 """Compile a code object into bytecode for writing out to a byte-compiled
485 file."""
486 data = bytearray(MAGIC_NUMBER)
487 data.extend(_w_long(mtime))
488 data.extend(_w_long(source_size))
489 data.extend(marshal.dumps(code))
490 return data
491
492
493def decode_source(source_bytes):
494 """Decode bytes representing source code and return the string.
495
496 Universal newline support is used in the decoding.
497 """
498 import tokenize # To avoid bootstrap issues.
499 source_bytes_readline = _io.BytesIO(source_bytes).readline
500 encoding = tokenize.detect_encoding(source_bytes_readline)
501 newline_decoder = _io.IncrementalNewlineDecoder(None, True)
502 return newline_decoder.decode(source_bytes.decode(encoding[0]))
503
504
505# Module specifications #######################################################
506
Eric Snow32439d62015-05-02 19:15:18 -0600507_POPULATE = object()
508
509
510def spec_from_file_location(name, location=None, *, loader=None,
511 submodule_search_locations=_POPULATE):
512 """Return a module spec based on a file location.
513
514 To indicate that the module is a package, set
515 submodule_search_locations to a list of directory paths. An
516 empty list is sufficient, though its not otherwise useful to the
517 import system.
518
519 The loader must take a spec as its only __init__() arg.
520
521 """
522 if location is None:
523 # The caller may simply want a partially populated location-
524 # oriented spec. So we set the location to a bogus value and
525 # fill in as much as we can.
526 location = '<unknown>'
527 if hasattr(loader, 'get_filename'):
528 # ExecutionLoader
529 try:
530 location = loader.get_filename(name)
531 except ImportError:
532 pass
533
534 # If the location is on the filesystem, but doesn't actually exist,
535 # we could return None here, indicating that the location is not
536 # valid. However, we don't have a good way of testing since an
537 # indirect location (e.g. a zip file or URL) will look like a
538 # non-existent file relative to the filesystem.
539
540 spec = _bootstrap.ModuleSpec(name, loader, origin=location)
541 spec._set_fileattr = True
542
543 # Pick a loader if one wasn't provided.
544 if loader is None:
545 for loader_class, suffixes in _get_supported_file_loaders():
546 if location.endswith(tuple(suffixes)):
547 loader = loader_class(name, location)
548 spec.loader = loader
549 break
550 else:
551 return None
552
553 # Set submodule_search_paths appropriately.
554 if submodule_search_locations is _POPULATE:
555 # Check the loader.
556 if hasattr(loader, 'is_package'):
557 try:
558 is_package = loader.is_package(name)
559 except ImportError:
560 pass
561 else:
562 if is_package:
563 spec.submodule_search_locations = []
564 else:
565 spec.submodule_search_locations = submodule_search_locations
566 if spec.submodule_search_locations == []:
567 if location:
568 dirname = _path_split(location)[0]
569 spec.submodule_search_locations.append(dirname)
570
571 return spec
572
573
574# Loaders #####################################################################
575
576class WindowsRegistryFinder:
577
578 """Meta path finder for modules declared in the Windows registry."""
579
580 REGISTRY_KEY = (
581 'Software\\Python\\PythonCore\\{sys_version}'
582 '\\Modules\\{fullname}')
583 REGISTRY_KEY_DEBUG = (
584 'Software\\Python\\PythonCore\\{sys_version}'
585 '\\Modules\\{fullname}\\Debug')
586 DEBUG_BUILD = False # Changed in _setup()
587
588 @classmethod
589 def _open_registry(cls, key):
590 try:
591 return _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, key)
592 except OSError:
593 return _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, key)
594
595 @classmethod
596 def _search_registry(cls, fullname):
597 if cls.DEBUG_BUILD:
598 registry_key = cls.REGISTRY_KEY_DEBUG
599 else:
600 registry_key = cls.REGISTRY_KEY
601 key = registry_key.format(fullname=fullname,
602 sys_version=sys.version[:3])
603 try:
604 with cls._open_registry(key) as hkey:
605 filepath = _winreg.QueryValue(hkey, '')
606 except OSError:
607 return None
608 return filepath
609
610 @classmethod
611 def find_spec(cls, fullname, path=None, target=None):
612 filepath = cls._search_registry(fullname)
613 if filepath is None:
614 return None
615 try:
616 _path_stat(filepath)
617 except OSError:
618 return None
619 for loader, suffixes in _get_supported_file_loaders():
620 if filepath.endswith(tuple(suffixes)):
Eric Snow183a9412015-05-15 21:54:59 -0600621 spec = _bootstrap.spec_from_loader(fullname,
622 loader(fullname, filepath),
623 origin=filepath)
Eric Snow32439d62015-05-02 19:15:18 -0600624 return spec
625
626 @classmethod
627 def find_module(cls, fullname, path=None):
628 """Find module named in the registry.
629
630 This method is deprecated. Use exec_module() instead.
631
632 """
633 spec = cls.find_spec(fullname, path)
634 if spec is not None:
635 return spec.loader
636 else:
637 return None
638
639
640class _LoaderBasics:
641
642 """Base class of common code needed by both SourceLoader and
643 SourcelessFileLoader."""
644
645 def is_package(self, fullname):
646 """Concrete implementation of InspectLoader.is_package by checking if
647 the path returned by get_filename has a filename of '__init__.py'."""
648 filename = _path_split(self.get_filename(fullname))[1]
649 filename_base = filename.rsplit('.', 1)[0]
650 tail_name = fullname.rpartition('.')[2]
651 return filename_base == '__init__' and tail_name != '__init__'
652
653 def create_module(self, spec):
654 """Use default semantics for module creation."""
655
656 def exec_module(self, module):
657 """Execute the module."""
658 code = self.get_code(module.__name__)
659 if code is None:
660 raise ImportError('cannot load module {!r} when get_code() '
661 'returns None'.format(module.__name__))
662 _bootstrap._call_with_frames_removed(exec, code, module.__dict__)
663
Eric Snow183a9412015-05-15 21:54:59 -0600664 def load_module(self, fullname):
665 return _bootstrap._load_module_shim(self, fullname)
Eric Snow32439d62015-05-02 19:15:18 -0600666
667
668class SourceLoader(_LoaderBasics):
669
670 def path_mtime(self, path):
671 """Optional method that returns the modification time (an int) for the
672 specified path, where path is a str.
673
674 Raises IOError when the path cannot be handled.
675 """
676 raise IOError
677
678 def path_stats(self, path):
679 """Optional method returning a metadata dict for the specified path
680 to by the path (str).
681 Possible keys:
682 - 'mtime' (mandatory) is the numeric timestamp of last source
683 code modification;
684 - 'size' (optional) is the size in bytes of the source code.
685
686 Implementing this method allows the loader to read bytecode files.
687 Raises IOError when the path cannot be handled.
688 """
689 return {'mtime': self.path_mtime(path)}
690
691 def _cache_bytecode(self, source_path, cache_path, data):
692 """Optional method which writes data (bytes) to a file path (a str).
693
694 Implementing this method allows for the writing of bytecode files.
695
696 The source path is needed in order to correctly transfer permissions
697 """
698 # For backwards compatibility, we delegate to set_data()
699 return self.set_data(cache_path, data)
700
701 def set_data(self, path, data):
702 """Optional method which writes data (bytes) to a file path (a str).
703
704 Implementing this method allows for the writing of bytecode files.
705 """
706
707
708 def get_source(self, fullname):
709 """Concrete implementation of InspectLoader.get_source."""
710 path = self.get_filename(fullname)
711 try:
712 source_bytes = self.get_data(path)
713 except OSError as exc:
714 raise ImportError('source not available through get_data()',
715 name=fullname) from exc
716 return decode_source(source_bytes)
717
718 def source_to_code(self, data, path, *, _optimize=-1):
719 """Return the code object compiled from source.
720
721 The 'data' argument can be any object type that compile() supports.
722 """
723 return _bootstrap._call_with_frames_removed(compile, data, path, 'exec',
724 dont_inherit=True, optimize=_optimize)
725
726 def get_code(self, fullname):
727 """Concrete implementation of InspectLoader.get_code.
728
729 Reading of bytecode requires path_stats to be implemented. To write
730 bytecode, set_data must also be implemented.
731
732 """
733 source_path = self.get_filename(fullname)
734 source_mtime = None
735 try:
736 bytecode_path = cache_from_source(source_path)
737 except NotImplementedError:
738 bytecode_path = None
739 else:
740 try:
741 st = self.path_stats(source_path)
742 except IOError:
743 pass
744 else:
745 source_mtime = int(st['mtime'])
746 try:
747 data = self.get_data(bytecode_path)
748 except OSError:
749 pass
750 else:
751 try:
752 bytes_data = _validate_bytecode_header(data,
753 source_stats=st, name=fullname,
754 path=bytecode_path)
755 except (ImportError, EOFError):
756 pass
757 else:
758 _verbose_message('{} matches {}', bytecode_path,
759 source_path)
760 return _compile_bytecode(bytes_data, name=fullname,
761 bytecode_path=bytecode_path,
762 source_path=source_path)
763 source_bytes = self.get_data(source_path)
764 code_object = self.source_to_code(source_bytes, source_path)
765 _verbose_message('code object from {}', source_path)
766 if (not sys.dont_write_bytecode and bytecode_path is not None and
767 source_mtime is not None):
768 data = _code_to_bytecode(code_object, source_mtime,
769 len(source_bytes))
770 try:
771 self._cache_bytecode(source_path, bytecode_path, data)
772 _verbose_message('wrote {!r}', bytecode_path)
773 except NotImplementedError:
774 pass
775 return code_object
776
777
778class FileLoader:
779
780 """Base file loader class which implements the loader protocol methods that
781 require file system usage."""
782
783 def __init__(self, fullname, path):
784 """Cache the module name and the path to the file found by the
785 finder."""
786 self.name = fullname
787 self.path = path
788
789 def __eq__(self, other):
790 return (self.__class__ == other.__class__ and
791 self.__dict__ == other.__dict__)
792
793 def __hash__(self):
794 return hash(self.name) ^ hash(self.path)
795
796 @_check_name
797 def load_module(self, fullname):
798 """Load a module from a file.
799
800 This method is deprecated. Use exec_module() instead.
801
802 """
803 # The only reason for this method is for the name check.
804 # Issue #14857: Avoid the zero-argument form of super so the implementation
805 # of that form can be updated without breaking the frozen module
806 return super(FileLoader, self).load_module(fullname)
807
808 @_check_name
809 def get_filename(self, fullname):
810 """Return the path to the source file as found by the finder."""
811 return self.path
812
813 def get_data(self, path):
814 """Return the data from path as raw bytes."""
815 with _io.FileIO(path, 'r') as file:
816 return file.read()
817
818
819class SourceFileLoader(FileLoader, SourceLoader):
820
821 """Concrete implementation of SourceLoader using the file system."""
822
823 def path_stats(self, path):
824 """Return the metadata for the path."""
825 st = _path_stat(path)
826 return {'mtime': st.st_mtime, 'size': st.st_size}
827
828 def _cache_bytecode(self, source_path, bytecode_path, data):
829 # Adapt between the two APIs
830 mode = _calc_mode(source_path)
831 return self.set_data(bytecode_path, data, _mode=mode)
832
833 def set_data(self, path, data, *, _mode=0o666):
834 """Write bytes data to a file."""
835 parent, filename = _path_split(path)
836 path_parts = []
837 # Figure out what directories are missing.
838 while parent and not _path_isdir(parent):
839 parent, part = _path_split(parent)
840 path_parts.append(part)
841 # Create needed directories.
842 for part in reversed(path_parts):
843 parent = _path_join(parent, part)
844 try:
845 _os.mkdir(parent)
846 except FileExistsError:
847 # Probably another Python process already created the dir.
848 continue
849 except OSError as exc:
850 # Could be a permission error, read-only filesystem: just forget
851 # about writing the data.
852 _verbose_message('could not create {!r}: {!r}', parent, exc)
853 return
854 try:
855 _write_atomic(path, data, _mode)
856 _verbose_message('created {!r}', path)
857 except OSError as exc:
858 # Same as above: just don't write the bytecode.
859 _verbose_message('could not create {!r}: {!r}', path, exc)
860
861
862class SourcelessFileLoader(FileLoader, _LoaderBasics):
863
864 """Loader which handles sourceless file imports."""
865
866 def get_code(self, fullname):
867 path = self.get_filename(fullname)
868 data = self.get_data(path)
869 bytes_data = _validate_bytecode_header(data, name=fullname, path=path)
870 return _compile_bytecode(bytes_data, name=fullname, bytecode_path=path)
871
872 def get_source(self, fullname):
873 """Return None as there is no source code."""
874 return None
875
876
877# Filled in by _setup().
878EXTENSION_SUFFIXES = []
879
880
Nick Coghland5cacbb2015-05-23 22:24:10 +1000881class ExtensionFileLoader(FileLoader, _LoaderBasics):
Eric Snow32439d62015-05-02 19:15:18 -0600882
883 """Loader for extension modules.
884
885 The constructor is designed to work with FileFinder.
886
887 """
888
889 def __init__(self, name, path):
890 self.name = name
891 self.path = path
892
893 def __eq__(self, other):
894 return (self.__class__ == other.__class__ and
895 self.__dict__ == other.__dict__)
896
897 def __hash__(self):
898 return hash(self.name) ^ hash(self.path)
899
Nick Coghland5cacbb2015-05-23 22:24:10 +1000900 def create_module(self, spec):
901 """Create an unitialized extension module"""
902 module = _bootstrap._call_with_frames_removed(
903 _imp.create_dynamic, spec)
904 _verbose_message('extension module {!r} loaded from {!r}',
905 spec.name, self.path)
Eric Snow32439d62015-05-02 19:15:18 -0600906 return module
907
Nick Coghland5cacbb2015-05-23 22:24:10 +1000908 def exec_module(self, module):
909 """Initialize an extension module"""
910 _bootstrap._call_with_frames_removed(_imp.exec_dynamic, module)
911 _verbose_message('extension module {!r} executed from {!r}',
912 self.name, self.path)
913
Eric Snow32439d62015-05-02 19:15:18 -0600914 def is_package(self, fullname):
915 """Return True if the extension module is a package."""
916 file_name = _path_split(self.path)[1]
917 return any(file_name == '__init__' + suffix
918 for suffix in EXTENSION_SUFFIXES)
919
920 def get_code(self, fullname):
921 """Return None as an extension module cannot create a code object."""
922 return None
923
924 def get_source(self, fullname):
925 """Return None as extension modules have no source code."""
926 return None
927
928 @_check_name
929 def get_filename(self, fullname):
930 """Return the path to the source file as found by the finder."""
931 return self.path
932
933
934class _NamespacePath:
935 """Represents a namespace package's path. It uses the module name
936 to find its parent module, and from there it looks up the parent's
937 __path__. When this changes, the module's own path is recomputed,
938 using path_finder. For top-level modules, the parent module's path
939 is sys.path."""
940
941 def __init__(self, name, path, path_finder):
942 self._name = name
943 self._path = path
944 self._last_parent_path = tuple(self._get_parent_path())
945 self._path_finder = path_finder
946
947 def _find_parent_path_names(self):
948 """Returns a tuple of (parent-module-name, parent-path-attr-name)"""
949 parent, dot, me = self._name.rpartition('.')
950 if dot == '':
951 # This is a top-level module. sys.path contains the parent path.
952 return 'sys', 'path'
953 # Not a top-level module. parent-module.__path__ contains the
954 # parent path.
955 return parent, '__path__'
956
957 def _get_parent_path(self):
958 parent_module_name, path_attr_name = self._find_parent_path_names()
959 return getattr(sys.modules[parent_module_name], path_attr_name)
960
961 def _recalculate(self):
962 # If the parent's path has changed, recalculate _path
963 parent_path = tuple(self._get_parent_path()) # Make a copy
964 if parent_path != self._last_parent_path:
965 spec = self._path_finder(self._name, parent_path)
966 # Note that no changes are made if a loader is returned, but we
967 # do remember the new parent path
968 if spec is not None and spec.loader is None:
969 if spec.submodule_search_locations:
970 self._path = spec.submodule_search_locations
971 self._last_parent_path = parent_path # Save the copy
972 return self._path
973
974 def __iter__(self):
975 return iter(self._recalculate())
976
977 def __len__(self):
978 return len(self._recalculate())
979
980 def __repr__(self):
981 return '_NamespacePath({!r})'.format(self._path)
982
983 def __contains__(self, item):
984 return item in self._recalculate()
985
986 def append(self, item):
987 self._path.append(item)
988
989
990# We use this exclusively in module_from_spec() for backward-compatibility.
991class _NamespaceLoader:
992 def __init__(self, name, path, path_finder):
993 self._path = _NamespacePath(name, path, path_finder)
994
995 @classmethod
996 def module_repr(cls, module):
997 """Return repr for the module.
998
999 The method is deprecated. The import machinery does the job itself.
1000
1001 """
1002 return '<module {!r} (namespace)>'.format(module.__name__)
1003
1004 def is_package(self, fullname):
1005 return True
1006
1007 def get_source(self, fullname):
1008 return ''
1009
1010 def get_code(self, fullname):
1011 return compile('', '<string>', 'exec', dont_inherit=True)
1012
1013 def create_module(self, spec):
1014 """Use default semantics for module creation."""
1015
1016 def exec_module(self, module):
1017 pass
1018
1019 def load_module(self, fullname):
1020 """Load a namespace module.
1021
1022 This method is deprecated. Use exec_module() instead.
1023
1024 """
1025 # The import system never calls this method.
1026 _verbose_message('namespace module loaded with path {!r}', self._path)
Eric Snow183a9412015-05-15 21:54:59 -06001027 return _bootstrap._load_module_shim(self, fullname)
Eric Snow32439d62015-05-02 19:15:18 -06001028
1029
1030# Finders #####################################################################
1031
1032class PathFinder:
1033
1034 """Meta path finder for sys.path and package __path__ attributes."""
1035
1036 @classmethod
1037 def invalidate_caches(cls):
1038 """Call the invalidate_caches() method on all path entry finders
1039 stored in sys.path_importer_caches (where implemented)."""
1040 for finder in sys.path_importer_cache.values():
1041 if hasattr(finder, 'invalidate_caches'):
1042 finder.invalidate_caches()
1043
1044 @classmethod
1045 def _path_hooks(cls, path):
1046 """Search sequence of hooks for a finder for 'path'.
1047
1048 If 'hooks' is false then use sys.path_hooks.
1049
1050 """
1051 if sys.path_hooks is not None and not sys.path_hooks:
1052 _warnings.warn('sys.path_hooks is empty', ImportWarning)
1053 for hook in sys.path_hooks:
1054 try:
1055 return hook(path)
1056 except ImportError:
1057 continue
1058 else:
1059 return None
1060
1061 @classmethod
1062 def _path_importer_cache(cls, path):
1063 """Get the finder for the path entry from sys.path_importer_cache.
1064
1065 If the path entry is not in the cache, find the appropriate finder
1066 and cache it. If no finder is available, store None.
1067
1068 """
1069 if path == '':
1070 try:
1071 path = _os.getcwd()
1072 except FileNotFoundError:
1073 # Don't cache the failure as the cwd can easily change to
1074 # a valid directory later on.
1075 return None
1076 try:
1077 finder = sys.path_importer_cache[path]
1078 except KeyError:
1079 finder = cls._path_hooks(path)
1080 sys.path_importer_cache[path] = finder
1081 return finder
1082
1083 @classmethod
1084 def _legacy_get_spec(cls, fullname, finder):
1085 # This would be a good place for a DeprecationWarning if
1086 # we ended up going that route.
1087 if hasattr(finder, 'find_loader'):
1088 loader, portions = finder.find_loader(fullname)
1089 else:
1090 loader = finder.find_module(fullname)
1091 portions = []
1092 if loader is not None:
Eric Snow183a9412015-05-15 21:54:59 -06001093 return _bootstrap.spec_from_loader(fullname, loader)
Eric Snow32439d62015-05-02 19:15:18 -06001094 spec = _bootstrap.ModuleSpec(fullname, None)
1095 spec.submodule_search_locations = portions
1096 return spec
1097
1098 @classmethod
1099 def _get_spec(cls, fullname, path, target=None):
1100 """Find the loader or namespace_path for this module/package name."""
1101 # If this ends up being a namespace package, namespace_path is
1102 # the list of paths that will become its __path__
1103 namespace_path = []
1104 for entry in path:
1105 if not isinstance(entry, (str, bytes)):
1106 continue
1107 finder = cls._path_importer_cache(entry)
1108 if finder is not None:
1109 if hasattr(finder, 'find_spec'):
1110 spec = finder.find_spec(fullname, target)
1111 else:
1112 spec = cls._legacy_get_spec(fullname, finder)
1113 if spec is None:
1114 continue
1115 if spec.loader is not None:
1116 return spec
1117 portions = spec.submodule_search_locations
1118 if portions is None:
1119 raise ImportError('spec missing loader')
1120 # This is possibly part of a namespace package.
1121 # Remember these path entries (if any) for when we
1122 # create a namespace package, and continue iterating
1123 # on path.
1124 namespace_path.extend(portions)
1125 else:
1126 spec = _bootstrap.ModuleSpec(fullname, None)
1127 spec.submodule_search_locations = namespace_path
1128 return spec
1129
1130 @classmethod
1131 def find_spec(cls, fullname, path=None, target=None):
1132 """find the module on sys.path or 'path' based on sys.path_hooks and
1133 sys.path_importer_cache."""
1134 if path is None:
1135 path = sys.path
1136 spec = cls._get_spec(fullname, path, target)
1137 if spec is None:
1138 return None
1139 elif spec.loader is None:
1140 namespace_path = spec.submodule_search_locations
1141 if namespace_path:
1142 # We found at least one namespace path. Return a
1143 # spec which can create the namespace package.
1144 spec.origin = 'namespace'
1145 spec.submodule_search_locations = _NamespacePath(fullname, namespace_path, cls._get_spec)
1146 return spec
1147 else:
1148 return None
1149 else:
1150 return spec
1151
1152 @classmethod
1153 def find_module(cls, fullname, path=None):
1154 """find the module on sys.path or 'path' based on sys.path_hooks and
1155 sys.path_importer_cache.
1156
1157 This method is deprecated. Use find_spec() instead.
1158
1159 """
1160 spec = cls.find_spec(fullname, path)
1161 if spec is None:
1162 return None
1163 return spec.loader
1164
1165
1166class FileFinder:
1167
1168 """File-based finder.
1169
1170 Interactions with the file system are cached for performance, being
1171 refreshed when the directory the finder is handling has been modified.
1172
1173 """
1174
1175 def __init__(self, path, *loader_details):
1176 """Initialize with the path to search on and a variable number of
1177 2-tuples containing the loader and the file suffixes the loader
1178 recognizes."""
1179 loaders = []
1180 for loader, suffixes in loader_details:
1181 loaders.extend((suffix, loader) for suffix in suffixes)
1182 self._loaders = loaders
1183 # Base (directory) path
1184 self.path = path or '.'
1185 self._path_mtime = -1
1186 self._path_cache = set()
1187 self._relaxed_path_cache = set()
1188
1189 def invalidate_caches(self):
1190 """Invalidate the directory mtime."""
1191 self._path_mtime = -1
1192
1193 find_module = _find_module_shim
1194
1195 def find_loader(self, fullname):
1196 """Try to find a loader for the specified module, or the namespace
1197 package portions. Returns (loader, list-of-portions).
1198
1199 This method is deprecated. Use find_spec() instead.
1200
1201 """
1202 spec = self.find_spec(fullname)
1203 if spec is None:
1204 return None, []
1205 return spec.loader, spec.submodule_search_locations or []
1206
1207 def _get_spec(self, loader_class, fullname, path, smsl, target):
1208 loader = loader_class(fullname, path)
1209 return spec_from_file_location(fullname, path, loader=loader,
1210 submodule_search_locations=smsl)
1211
1212 def find_spec(self, fullname, target=None):
1213 """Try to find a loader for the specified module, or the namespace
1214 package portions. Returns (loader, list-of-portions)."""
1215 is_namespace = False
1216 tail_module = fullname.rpartition('.')[2]
1217 try:
1218 mtime = _path_stat(self.path or _os.getcwd()).st_mtime
1219 except OSError:
1220 mtime = -1
1221 if mtime != self._path_mtime:
1222 self._fill_cache()
1223 self._path_mtime = mtime
1224 # tail_module keeps the original casing, for __file__ and friends
1225 if _relax_case():
1226 cache = self._relaxed_path_cache
1227 cache_module = tail_module.lower()
1228 else:
1229 cache = self._path_cache
1230 cache_module = tail_module
1231 # Check if the module is the name of a directory (and thus a package).
1232 if cache_module in cache:
1233 base_path = _path_join(self.path, tail_module)
1234 for suffix, loader_class in self._loaders:
1235 init_filename = '__init__' + suffix
1236 full_path = _path_join(base_path, init_filename)
1237 if _path_isfile(full_path):
1238 return self._get_spec(loader_class, fullname, full_path, [base_path], target)
1239 else:
1240 # If a namespace package, return the path if we don't
1241 # find a module in the next section.
1242 is_namespace = _path_isdir(base_path)
1243 # Check for a file w/ a proper suffix exists.
1244 for suffix, loader_class in self._loaders:
1245 full_path = _path_join(self.path, tail_module + suffix)
1246 _verbose_message('trying {}'.format(full_path), verbosity=2)
1247 if cache_module + suffix in cache:
1248 if _path_isfile(full_path):
1249 return self._get_spec(loader_class, fullname, full_path, None, target)
1250 if is_namespace:
1251 _verbose_message('possible namespace for {}'.format(base_path))
1252 spec = _bootstrap.ModuleSpec(fullname, None)
1253 spec.submodule_search_locations = [base_path]
1254 return spec
1255 return None
1256
1257 def _fill_cache(self):
1258 """Fill the cache of potential modules and packages for this directory."""
1259 path = self.path
1260 try:
1261 contents = _os.listdir(path or _os.getcwd())
1262 except (FileNotFoundError, PermissionError, NotADirectoryError):
1263 # Directory has either been removed, turned into a file, or made
1264 # unreadable.
1265 contents = []
1266 # We store two cached versions, to handle runtime changes of the
1267 # PYTHONCASEOK environment variable.
1268 if not sys.platform.startswith('win'):
1269 self._path_cache = set(contents)
1270 else:
1271 # Windows users can import modules with case-insensitive file
1272 # suffixes (for legacy reasons). Make the suffix lowercase here
1273 # so it's done once instead of for every import. This is safe as
1274 # the specified suffixes to check against are always specified in a
1275 # case-sensitive manner.
1276 lower_suffix_contents = set()
1277 for item in contents:
1278 name, dot, suffix = item.partition('.')
1279 if dot:
1280 new_name = '{}.{}'.format(name, suffix.lower())
1281 else:
1282 new_name = name
1283 lower_suffix_contents.add(new_name)
1284 self._path_cache = lower_suffix_contents
1285 if sys.platform.startswith(_CASE_INSENSITIVE_PLATFORMS):
1286 self._relaxed_path_cache = {fn.lower() for fn in contents}
1287
1288 @classmethod
1289 def path_hook(cls, *loader_details):
1290 """A class method which returns a closure to use on sys.path_hook
1291 which will return an instance using the specified loaders and the path
1292 called on the closure.
1293
1294 If the path called on the closure is not a directory, ImportError is
1295 raised.
1296
1297 """
1298 def path_hook_for_FileFinder(path):
1299 """Path hook for importlib.machinery.FileFinder."""
1300 if not _path_isdir(path):
1301 raise ImportError('only directories are supported', path=path)
1302 return cls(path, *loader_details)
1303
1304 return path_hook_for_FileFinder
1305
1306 def __repr__(self):
1307 return 'FileFinder({!r})'.format(self.path)
1308
1309
1310# Import setup ###############################################################
1311
1312def _fix_up_module(ns, name, pathname, cpathname=None):
1313 # This function is used by PyImport_ExecCodeModuleObject().
1314 loader = ns.get('__loader__')
1315 spec = ns.get('__spec__')
1316 if not loader:
1317 if spec:
1318 loader = spec.loader
1319 elif pathname == cpathname:
1320 loader = SourcelessFileLoader(name, pathname)
1321 else:
1322 loader = SourceFileLoader(name, pathname)
1323 if not spec:
1324 spec = spec_from_file_location(name, pathname, loader=loader)
1325 try:
1326 ns['__spec__'] = spec
1327 ns['__loader__'] = loader
1328 ns['__file__'] = pathname
1329 ns['__cached__'] = cpathname
1330 except Exception:
1331 # Not important enough to report.
1332 pass
1333
1334
1335def _get_supported_file_loaders():
1336 """Returns a list of file-based module loaders.
1337
1338 Each item is a tuple (loader, suffixes).
1339 """
1340 extensions = ExtensionFileLoader, _imp.extension_suffixes()
1341 source = SourceFileLoader, SOURCE_SUFFIXES
1342 bytecode = SourcelessFileLoader, BYTECODE_SUFFIXES
1343 return [extensions, source, bytecode]
1344
1345
1346def _setup(_bootstrap_module):
1347 """Setup the path-based importers for importlib by importing needed
1348 built-in modules and injecting them into the global namespace.
1349
1350 Other components are extracted from the core bootstrap module.
1351
1352 """
1353 global sys, _imp, _bootstrap
1354 _bootstrap = _bootstrap_module
1355 sys = _bootstrap.sys
1356 _imp = _bootstrap._imp
1357
1358 # Directly load built-in modules needed during bootstrap.
1359 self_module = sys.modules[__name__]
1360 for builtin_name in ('_io', '_warnings', 'builtins', 'marshal'):
1361 if builtin_name not in sys.modules:
1362 builtin_module = _bootstrap._builtin_from_name(builtin_name)
1363 else:
1364 builtin_module = sys.modules[builtin_name]
1365 setattr(self_module, builtin_name, builtin_module)
1366
1367 # Directly load the os module (needed during bootstrap).
1368 os_details = ('posix', ['/']), ('nt', ['\\', '/'])
1369 for builtin_os, path_separators in os_details:
1370 # Assumption made in _path_join()
1371 assert all(len(sep) == 1 for sep in path_separators)
1372 path_sep = path_separators[0]
1373 if builtin_os in sys.modules:
1374 os_module = sys.modules[builtin_os]
1375 break
1376 else:
1377 try:
1378 os_module = _bootstrap._builtin_from_name(builtin_os)
1379 break
1380 except ImportError:
1381 continue
1382 else:
1383 raise ImportError('importlib requires posix or nt')
1384 setattr(self_module, '_os', os_module)
1385 setattr(self_module, 'path_sep', path_sep)
1386 setattr(self_module, 'path_separators', ''.join(path_separators))
1387
1388 # Directly load the _thread module (needed during bootstrap).
1389 try:
1390 thread_module = _bootstrap._builtin_from_name('_thread')
1391 except ImportError:
1392 # Python was built without threads
1393 thread_module = None
1394 setattr(self_module, '_thread', thread_module)
1395
1396 # Directly load the _weakref module (needed during bootstrap).
1397 weakref_module = _bootstrap._builtin_from_name('_weakref')
1398 setattr(self_module, '_weakref', weakref_module)
1399
1400 # Directly load the winreg module (needed during bootstrap).
1401 if builtin_os == 'nt':
1402 winreg_module = _bootstrap._builtin_from_name('winreg')
1403 setattr(self_module, '_winreg', winreg_module)
1404
1405 # Constants
1406 setattr(self_module, '_relax_case', _make_relax_case())
1407 EXTENSION_SUFFIXES.extend(_imp.extension_suffixes())
1408 if builtin_os == 'nt':
1409 SOURCE_SUFFIXES.append('.pyw')
1410 if '_d.pyd' in EXTENSION_SUFFIXES:
1411 WindowsRegistryFinder.DEBUG_BUILD = True
1412
1413
1414def _install(_bootstrap_module):
1415 """Install the path-based import components."""
1416 _setup(_bootstrap_module)
1417 supported_loaders = _get_supported_file_loaders()
1418 sys.path_hooks.extend([FileFinder.path_hook(*supported_loaders)])
1419 if _os.__name__ == 'nt':
1420 sys.meta_path.append(WindowsRegistryFinder)
1421 sys.meta_path.append(PathFinder)
1422
1423 # XXX We expose a couple of classes in _bootstrap for the sake of
1424 # a setuptools bug (https://bitbucket.org/pypa/setuptools/issue/378).
1425 _bootstrap_module.FileFinder = FileFinder
1426 _bootstrap_module.SourceFileLoader = SourceFileLoader