pathlib: import signature and docs for import_path

This commit is contained in:
Bruno Oliveira 2024-03-02 11:19:57 -03:00
parent 5746b8e696
commit 199d4e2b73
1 changed files with 17 additions and 13 deletions

View File

@ -484,26 +484,31 @@ class ImportPathMismatchError(ImportError):
def import_path( def import_path(
p: Union[str, "os.PathLike[str]"], path: Union[str, "os.PathLike[str]"],
*, *,
mode: Union[str, ImportMode] = ImportMode.prepend, mode: Union[str, ImportMode] = ImportMode.prepend,
root: Path, root: Path,
) -> ModuleType: ) -> ModuleType:
"""Import and return a module from the given path, which can be a file (a module) or """
Import and return a module from the given path, which can be a file (a module) or
a directory (a package). a directory (a package).
The import mechanism used is controlled by the `mode` parameter: :param path:
Path to the file to import.
* `mode == ImportMode.prepend`: the directory containing the module (or package, taking :param mode:
`__init__.py` files into account) will be put at the *start* of `sys.path` before Controls the underlying import mechanism that will be used:
being imported with `importlib.import_module`.
* `mode == ImportMode.append`: same as `prepend`, but the directory will be appended * ImportMode.prepend: the directory containing the module (or package, taking
to the end of `sys.path`, if not already in `sys.path`. `__init__.py` files into account) will be put at the *start* of `sys.path` before
being imported with `importlib.import_module`.
* `mode == ImportMode.importlib`: uses more fine control mechanisms provided by `importlib` * ImportMode.append: same as `prepend`, but the directory will be appended
to import the module, which avoids having to muck with `sys.path` at all. It effectively to the end of `sys.path`, if not already in `sys.path`.
allows having same-named test modules in different places.
* ImportMode.importlib: uses more fine control mechanisms provided by `importlib`
to import the module, which avoids having to muck with `sys.path` at all. It effectively
allows having same-named test modules in different places.
:param root: :param root:
Used as an anchor when mode == ImportMode.importlib to obtain Used as an anchor when mode == ImportMode.importlib to obtain
@ -514,10 +519,9 @@ def import_path(
If after importing the given `path` and the module `__file__` If after importing the given `path` and the module `__file__`
are different. Only raised in `prepend` and `append` modes. are different. Only raised in `prepend` and `append` modes.
""" """
path = Path(path)
mode = ImportMode(mode) mode = ImportMode(mode)
path = Path(p)
if not path.exists(): if not path.exists():
raise ImportError(path) raise ImportError(path)