Import and return a module from the given path, which can be a file (a module) or a directory (a package). :param path: Path to the file to import. :param mode: Controls the underlying import mechanism that will be used: * ImportMode.prepend: the directory
(
path: str | os.PathLike[str],
*,
mode: str | ImportMode = ImportMode.prepend,
root: Path,
consider_namespace_packages: bool,
)
| 500 | |
| 501 | |
| 502 | def import_path( |
| 503 | path: str | os.PathLike[str], |
| 504 | *, |
| 505 | mode: str | ImportMode = ImportMode.prepend, |
| 506 | root: Path, |
| 507 | consider_namespace_packages: bool, |
| 508 | ) -> ModuleType: |
| 509 | class="st">""" |
| 510 | Import and return a module from the given path, which can be a file (a module) or |
| 511 | a directory (a package). |
| 512 | |
| 513 | :param path: |
| 514 | Path to the file to import. |
| 515 | |
| 516 | :param mode: |
| 517 | Controls the underlying import mechanism that will be used: |
| 518 | |
| 519 | * ImportMode.prepend: the directory containing the module (or package, taking |
| 520 | `__init__.py` files into account) will be put at the *start* of `sys.path` before |
| 521 | being imported with `importlib.import_module`. |
| 522 | |
| 523 | * ImportMode.append: same as `prepend`, but the directory will be appended |
| 524 | to the end of `sys.path`, if not already in `sys.path`. |
| 525 | |
| 526 | * ImportMode.importlib: uses more fine control mechanisms provided by `importlib` |
| 527 | to import the module, which avoids having to muck with `sys.path` at all. It effectively |
| 528 | allows having same-named test modules in different places. |
| 529 | |
| 530 | :param root: |
| 531 | Used as an anchor when mode == ImportMode.importlib to obtain |
| 532 | a unique name for the module being imported so it can safely be stored |
| 533 | into ``sys.modules``. |
| 534 | |
| 535 | :param consider_namespace_packages: |
| 536 | If True, consider namespace packages when resolving module names. |
| 537 | |
| 538 | :raises ImportPathMismatchError: |
| 539 | If after importing the given `path` and the module `__file__` |
| 540 | are different. Only raised in `prepend` and `append` modes. |
| 541 | class="st">""" |
| 542 | path = Path(path) |
| 543 | mode = ImportMode(mode) |
| 544 | |
| 545 | if not path.exists(): |
| 546 | raise ImportError(path) |
| 547 | |
| 548 | if mode is ImportMode.importlib: |
| 549 | class="cm"># Try to import this module using the standard import mechanisms, but |
| 550 | class="cm"># without touching sys.path. |
| 551 | try: |
| 552 | _, module_name = resolve_pkg_root_and_module_name( |
| 553 | path, consider_namespace_packages=consider_namespace_packages |
| 554 | ) |
| 555 | except CouldNotResolvePathError: |
| 556 | pass |
| 557 | else: |
| 558 | class="cm"># If the given module name is already in sys.modules, do not import it again. |
| 559 | with contextlib.suppress(KeyError): |