MCPcopy
hub / github.com/pytest-dev/pytest / module_name_from_path

Function module_name_from_path

src/_pytest/pathlib.py:761–789  ·  src/_pytest/pathlib.py::module_name_from_path

Return a dotted module name based on the given path, anchored on root. For example: path="projects/src/tests/test_foo.py" and root="/projects", the resulting module name will be "src.tests.test_foo".

(path: Path, root: Path)

Source from the content-addressed store, hash-verified

759
760
761def module_name_from_path(path: Path, root: Path) -> str:
762 class="st">"""
763 Return a dotted module name based on the given path, anchored on root.
764
765 For example: path=class="st">"projects/src/tests/test_foo.py" and root=class="st">"/projects", the
766 resulting module name will be class="st">"src.tests.test_foo".
767 class="st">"""
768 path = path.with_suffix(class="st">"")
769 try:
770 relative_path = path.relative_to(root)
771 except ValueError:
772 class="cm"># If we can't get a relative path to root, use the full path, except
773 class="cm"># for the first part (class="st">"d:\\" or class="st">"/" depending on the platform, for example).
774 path_parts = path.parts[1:]
775 else:
776 class="cm"># Use the parts for the relative path to the root path.
777 path_parts = relative_path.parts
778
779 class="cm"># Module name for packages do not contain the __init__ file, unless
780 class="cm"># the `__init__.py` file is at the root.
781 if len(path_parts) >= 2 and path_parts[-1] == class="st">"__init__":
782 path_parts = path_parts[:-1]
783
784 class="cm"># Module names cannot contain class="st">".", normalize them to class="st">"_". This prevents
785 class="cm"># a directory having a class="st">"." in the name (class="st">".env.310" for example) causing extra intermediate modules.
786 class="cm"># Also, important to replace class="st">"." at the start of paths, as those are considered relative imports.
787 path_parts = tuple(x.replace(class="st">".", class="st">"_") for x in path_parts)
788
789 return class="st">".".join(path_parts)
790
791
792def insert_missing_modules(modules: dict[str, ModuleType], module_name: str) -> None:

Callers 3

simple_moduleMethod · 0.90
import_pathFunction · 0.85

Calls 1

joinMethod · 0.80

Tested by 2

simple_moduleMethod · 0.72