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

Method syspath_prepend

src/_pytest/monkeypatch.py:337–377  ·  view source on GitHub ↗

Prepend ``path`` to ``sys.path`` list of import locations.

(self, path)

Source from the content-addressed store, hash-verified

335 self.delitem(environ, name, raising=raising)
336
337 def syspath_prepend(self, path) -> None:
338 """Prepend ``path`` to ``sys.path`` list of import locations."""
339 if self._savesyspath is None:
340 self._savesyspath = sys.path[:]
341 sys.path.insert(0, str(path))
342
343 # https://github.com/pypa/setuptools/blob/d8b901bc/docs/pkg_resources.txt#L162-L171
344 # this is only needed when pkg_resources was already loaded by the namespace package
345 if "pkg_resources" in sys.modules:
346 import pkg_resources
347 from pkg_resources import fixup_namespace_packages
348
349 # Only issue deprecation warning if this call would actually have an
350 # effect for this specific path.
351 if (
352 hasattr(pkg_resources, "_namespace_packages")
353 and pkg_resources._namespace_packages
354 ):
355 path_obj = Path(str(path))
356 for ns_pkg in pkg_resources._namespace_packages:
357 if ns_pkg is None:
358 continue
359 ns_pkg_path = path_obj / ns_pkg.replace(".", os.sep)
360 if ns_pkg_path.is_dir():
361 warnings.warn(
362 MONKEYPATCH_LEGACY_NAMESPACE_PACKAGES, stacklevel=2
363 )
364 break
365
366 fixup_namespace_packages(str(path))
367
368 # A call to syspathinsert() usually means that the caller wants to
369 # import some dynamically created files, thus with python3 we
370 # invalidate its import caches.
371 # This is especially important when any namespace package is in use,
372 # since then the mtime based FileFinder cache (that gets created in
373 # this case already) gets not invalidated when writing the new files
374 # quickly afterwards.
375 from importlib import invalidate_caches
376
377 invalidate_caches()
378
379 def chdir(self, path: str | os.PathLike[str]) -> None:
380 """Change the current working directory to the specified path.

Calls 2

insertMethod · 0.80
warnMethod · 0.45