| 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 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
_bootstrap = None |
| 24 |
|
| 25 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 111 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 195 |
|
| 196 |
with _io.FileIO(fd, 'wb') as file: |
| 197 |
bytes_written = file.write(data) |
| 198 |
if bytes_written != len(data): |
| 199 |
|
| 200 |
|
| 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 |
|
| 215 |
|
| 216 |
|
| 217 |
|
| 218 |
|
| 219 |
|
| 220 |
|
| 221 |
|
| 222 |
|
| 223 |
|
| 224 |
|
| 225 |
|
| 226 |
|
| 227 |
|
| 228 |
|
| 229 |
|
| 230 |
|
| 231 |
|
| 232 |
|
| 233 |
|
| 234 |
|
| 235 |
|
| 236 |
|
| 237 |
|
| 238 |
|
| 239 |
|
| 240 |
|
| 241 |
|
| 242 |
|
| 243 |
|
| 244 |
|
| 245 |
|
| 246 |
|
| 247 |
|
| 248 |
|
| 249 |
|
| 250 |
|
| 251 |
|
| 252 |
|
| 253 |
|
| 254 |
|
| 255 |
|
| 256 |
|
| 257 |
|
| 258 |
|
| 259 |
|
| 260 |
|
| 261 |
|
| 262 |
|
| 263 |
|
| 264 |
|
| 265 |
|
| 266 |
|
| 267 |
|
| 268 |
|
| 269 |
|
| 270 |
|
| 271 |
|
| 272 |
|
| 273 |
|
| 274 |
|
| 275 |
|
| 276 |
|
| 277 |
|
| 278 |
|
| 279 |
|
| 280 |
|
| 281 |
|
| 282 |
|
| 283 |
|
| 284 |
|
| 285 |
|
| 286 |
|
| 287 |
|
| 288 |
|
| 289 |
|
| 290 |
|
| 291 |
|
| 292 |
|
| 293 |
|
| 294 |
|
| 295 |
|
| 296 |
|
| 297 |
|
| 298 |
|
| 299 |
|
| 300 |
|
| 301 |
|
| 302 |
|
| 303 |
|
| 304 |
|
| 305 |
|
| 306 |
|
| 307 |
|
| 308 |
|
| 309 |
|
| 310 |
|
| 311 |
|
| 312 |
|
| 313 |
|
| 314 |
|
| 315 |
|
| 316 |
|
| 317 |
|
| 318 |
|
| 319 |
|
| 320 |
|
| 321 |
|
| 322 |
|
| 323 |
|
| 324 |
|
| 325 |
|
| 326 |
|
| 327 |
|
| 328 |
|
| 329 |
|
| 330 |
|
| 331 |
|
| 332 |
|
| 333 |
|
| 334 |
|
| 335 |
|
| 336 |
|
| 337 |
|
| 338 |
|
| 339 |
|
| 340 |
|
| 341 |
|
| 342 |
|
| 343 |
|
| 344 |
|
| 345 |
|
| 346 |
|
| 347 |
|
| 348 |
|
| 349 |
|
| 350 |
|
| 351 |
|
| 352 |
|
| 353 |
|
| 354 |
|
| 355 |
|
| 356 |
|
| 357 |
|
| 358 |
|
| 359 |
|
| 360 |
|
| 361 |
|
| 362 |
|
| 363 |
|
| 364 |
|
| 365 |
|
| 366 |
|
| 367 |
|
| 368 |
|
| 369 |
|
| 370 |
|
| 371 |
|
| 372 |
|
| 373 |
|
| 374 |
|
| 375 |
|
| 376 |
|
| 377 |
|
| 378 |
|
| 379 |
|
| 380 |
|
| 381 |
|
| 382 |
|
| 383 |
|
| 384 |
|
| 385 |
|
| 386 |
|
| 387 |
|
| 388 |
|
| 389 |
|
| 390 |
|
| 391 |
|
| 392 |
|
| 393 |
|
| 394 |
|
| 395 |
|
| 396 |
|
| 397 |
|
| 398 |
|
| 399 |
|
| 400 |
|
| 401 |
|
| 402 |
|
| 403 |
|
| 404 |
|
| 405 |
|
| 406 |
|
| 407 |
|
| 408 |
|
| 409 |
|
| 410 |
|
| 411 |
|
| 412 |
|
| 413 |
|
| 414 |
|
| 415 |
|
| 416 |
|
| 417 |
|
| 418 |
|
| 419 |
|
| 420 |
|
| 421 |
|
| 422 |
|
| 423 |
|
| 424 |
|
| 425 |
|
| 426 |
|
| 427 |
|
| 428 |
|
| 429 |
|
| 430 |
|
| 431 |
|
| 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') |
| 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 |
|
| 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 |
|
| 497 |
|
| 498 |
|
| 499 |
|
| 500 |
|
| 501 |
|
| 502 |
|
| 503 |
|
| 504 |
if not _path_isabs(head): |
| 505 |
head = _path_join(_os.getcwd(), head) |
| 506 |
|
| 507 |
|
| 508 |
|
| 509 |
|
| 510 |
if head[1] == ':' and head[0] not in path_separators: |
| 511 |
head = head[2:] |
| 512 |
|
| 513 |
|
| 514 |
|
| 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 |
|
| 601 |
|
| 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 |
|
| 623 |
|
| 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 |
|
| 648 |
|
| 649 |
|
| 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 |
|
| 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 |
| 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 |
|
| 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 |
|
| 807 |
|
| 808 |
|
| 809 |
location = '<unknown>' |
| 810 |
if hasattr(loader, 'get_filename'): |
| 811 |
|
| 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 |
|
| 825 |
|
| 826 |
|
| 827 |
|
| 828 |
|
| 829 |
|
| 830 |
spec = _bootstrap.ModuleSpec(name, loader, origin=location) |
| 831 |
spec._set_fileattr = True |
| 832 |
|
| 833 |
|
| 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 |
|
| 844 |
if submodule_search_locations is _POPULATE: |
| 845 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 1133 |
|
| 1134 |
|
| 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 |
|
| 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 |
|
| 1176 |
while parent and not _path_isdir(parent): |
| 1177 |
parent, part = _path_split(parent) |
| 1178 |
path_parts.append(part) |
| 1179 |
|
| 1180 |
for part in reversed(path_parts): |
| 1181 |
parent = _path_join(parent, part) |
| 1182 |
try: |
| 1183 |
_os.mkdir(parent) |
| 1184 |
except FileExistsError: |
| 1185 |
|
| 1186 |
continue |
| 1187 |
except OSError as exc: |
| 1188 |
|
| 1189 |
|
| 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 |
|
| 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 |
|
| 1210 |
|
| 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 |
|
| 1288 |
|
| 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 |
|
| 1303 |
return 'sys', 'path' |
| 1304 |
|
| 1305 |
|
| 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 |
|
| 1314 |
parent_path = tuple(self._get_parent_path()) |
| 1315 |
if parent_path != self._last_parent_path or self._epoch != self._last_epoch: |
| 1316 |
spec = self._path_finder(self._name, parent_path) |
| 1317 |
|
| 1318 |
|
| 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 |
| 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 |
|
| 1349 |
|
| 1350 |
|
| 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 |
|
| 1388 |
_bootstrap._verbose_message('namespace module loaded with path {!r}', |
| 1389 |
self._path) |
| 1390 |
|
| 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 |
|
| 1399 |
_NamespaceLoader = NamespaceLoader |
| 1400 |
|
| 1401 |
|
| 1402 |
|
| 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 |
|
| 1414 |
|
| 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 |
|
| 1420 |
|
| 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 |
|
| 1452 |
|
| 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 |
|
| 1464 |
|
| 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 |
|
| 1486 |
|
| 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 |
|
| 1505 |
|
| 1506 |
|
| 1507 |
|
| 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 |
|
| 1529 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 1653 |
|
| 1654 |
is_namespace = _path_isdir(base_path) |
| 1655 |
|
| 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 |
|
| 1680 |
|
| 1681 |
contents = [] |
| 1682 |
|
| 1683 |
|
| 1684 |
if not sys.platform.startswith('win'): |
| 1685 |
self._path_cache = set(contents) |
| 1686 |
else: |
| 1687 |
|
| 1688 |
|
| 1689 |
|
| 1690 |
|
| 1691 |
|
| 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 |
|
| 1727 |
|
| 1728 |
def _fix_up_module(ns, name, pathname, cpathname=None): |
| 1729 |
|
| 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 |
|
| 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) |