Debian Codegraph @

lib-python/3/importlib/_bootstrap_external.py

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