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