Skip to content

Commit fb66ca9

Browse files
committed
monkeypatch.syspath_prepend: Skip fixup_namespace_packages if pkg_resources not imported
Calling pkg_resources.fixup_namespace_packages() is only needed for packages that use pkg_resources.declare_namespace() and hence they already imported pkg_resources. When pkg_resources is not imported, we don't need to use it. This avoids an unneeded runtime dependency on setuptools. The code is tested by test_syspath_prepend_with_namespace_packages, behavior should remain unchanged, hence no new test was added. When people drop pkg_resources from sys.modules, they are on their own. If someone has a actual use case making this valid to support, they can come in and provide a test, a reference and a fix.
1 parent 0061ec5 commit fb66ca9

File tree

2 files changed

+9
-2
lines changed

2 files changed

+9
-2
lines changed

changelog/8503.trivial.rst

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
:meth:`_pytest.monkeypatch.syspath_prepend` no longer fails when
2+
``setuptools`` is not installed.
3+
It now only calls ``pkg_resources.fixup_namespace_packages()`` if
4+
``pkg_resources`` was previously imported, because it is not needed otherwise.

src/_pytest/monkeypatch.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -312,14 +312,17 @@ def delenv(self, name: str, raising: bool = True) -> None:
312312

313313
def syspath_prepend(self, path) -> None:
314314
"""Prepend ``path`` to ``sys.path`` list of import locations."""
315-
from pkg_resources import fixup_namespace_packages
316315

317316
if self._savesyspath is None:
318317
self._savesyspath = sys.path[:]
319318
sys.path.insert(0, str(path))
320319

321320
# https://github.com/pypa/setuptools/blob/d8b901bc/docs/pkg_resources.txt#L162-L171
322-
fixup_namespace_packages(str(path))
321+
# this is only needed when pkg_resources was already loaded by the namespace package
322+
if "pkg_resources" in sys.modules:
323+
from pkg_resources import fixup_namespace_packages
324+
325+
fixup_namespace_packages(str(path))
323326

324327
# A call to syspathinsert() usually means that the caller wants to
325328
# import some dynamically created files, thus with python3 we

0 commit comments

Comments
 (0)