Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions docs/changelog/+relative-exe-cache.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
:meth:`~python_discovery.PythonInfo.from_exe` now keys its caches on the absolute executable path and copies cached
instances when ``executable`` differs, so relative paths follow working-directory changes and alternate path spellings
do not mutate previously returned :class:`~python_discovery.PythonInfo` objects.
14 changes: 9 additions & 5 deletions src/python_discovery/_cached_py_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from __future__ import annotations

__lazy_modules__ = [
"copy",
"hashlib",
"io",
"pkgutil",
Expand All @@ -17,6 +18,7 @@
f"{__spec__.parent}._windows", # ty: ignore[unresolved-attribute] # imported modules have a spec
]

import copy
import hashlib
import logging
import os
Expand Down Expand Up @@ -62,7 +64,7 @@ class CacheEntryMeta(TypedDict):


_CACHE: Final[OrderedDict[tuple[Path, str | None], PythonInfo | Exception]] = OrderedDict()
_CACHE[Path(sys.executable), None] = PythonInfo()
_CACHE[Path(sys.executable).absolute(), None] = PythonInfo()
_LOGGER: Final[logging.Logger] = logging.getLogger(__name__)
_PY_INFO_SCRIPT: Final[Path] = Path(__file__).resolve().parent / "_py_info_collect.py"
_MAX_QUERY_OUTPUT: Final[int] = 1 << 20
Expand Down Expand Up @@ -104,17 +106,19 @@ def _get_from_cache( # ruff:ignore[too-many-arguments] each argument is a separ
ignore_cache: bool,
executable_args: str | None,
) -> PythonInfo | Exception:
key = Path(exe), executable_args
path = Path(exe).absolute()
key = path, executable_args
if not ignore_cache and key in _CACHE:
result = _CACHE[key]
else:
result = _get_via_file_cache(cls, cache, key[0], exe, env, executable_args=executable_args)
if _cacheable_result(key[0], result):
result = _get_via_file_cache(cls, cache, path, exe, env, executable_args=executable_args)
if _cacheable_result(path, result):
_CACHE[key] = result
else:
_CACHE.pop(key, None)
# with launcher arguments the queried binary is not the interpreter, so keep the one the query reported
if isinstance(result, PythonInfo) and executable_args is None:
if isinstance(result, PythonInfo) and executable_args is None and result.executable != exe:
result = copy.copy(result)
result.executable = exe
return result

Expand Down
44 changes: 43 additions & 1 deletion tests/python_discovery/test_cached_py_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from io import StringIO
from os import read
from pathlib import Path
from subprocess import DEVNULL, PIPE, Popen, TimeoutExpired, list2cmdline
from subprocess import DEVNULL, PIPE, Popen, TimeoutExpired, check_call, list2cmdline
from threading import enumerate as active_threads
from time import monotonic
from typing import TYPE_CHECKING, Final
Expand Down Expand Up @@ -773,3 +773,45 @@ def test_from_exe_timeout_with_inherited_pipes(tmp_path: Path) -> None:

assert result is None
assert monotonic() - started < 2.5


@pytest.mark.parametrize("ignore_cache", [pytest.param(False, id="memory"), pytest.param(True, id="disk")])
def test_from_exe_relative_path_follows_working_directory(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ignore_cache: bool
) -> None:
rel_exe = Path("venv/Scripts/python.exe" if sys.platform == "win32" else "venv/bin/python")
first, second = tmp_path / "first", tmp_path / "second"
check_call([sys.executable, "-m", "venv", "--without-pip", str(first / "venv"), str(second / "venv")])
if sys.platform == "win32": # pragma: win32 cover
mtime = (first / rel_exe).stat().st_mtime
os.utime(second / rel_exe, (mtime, mtime))
cache = DiskCache(tmp_path / "cache")

monkeypatch.chdir(first)
earlier = PythonInfo.from_exe(str(rel_exe), cache, ignore_cache=ignore_cache, resolve_to_host=False)
monkeypatch.chdir(second)
later = PythonInfo.from_exe(str(rel_exe), cache, ignore_cache=ignore_cache, resolve_to_host=False)

assert earlier is not None
assert later is not None
assert (earlier.prefix, earlier.executable, later.prefix, later.executable) == (
str(first / "venv"),
str(rel_exe),
str(second / "venv"),
str(rel_exe),
)


def test_from_exe_leaves_cached_executable_untouched(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(PythonInfo, "_current", None)
current = PythonInfo.current()
exe_path = Path(sys.executable)
dotted = f"{exe_path.parent}{os.sep}.{os.sep}{exe_path.name}"

via_dot = PythonInfo.from_exe(dotted, resolve_to_host=False)
monkeypatch.chdir(exe_path.parent)
via_rel = PythonInfo.from_exe(exe_path.name, resolve_to_host=False)

assert via_dot is not None
assert via_rel is not None
assert (current.executable, via_dot.executable, via_rel.executable) == (sys.executable, dotted, exe_path.name)