API reference

Self-contained Python interpreter discovery.

class python_discovery.ContentStore(*args, **kwargs)

Bases: Protocol

A store for reading and writing cached content.

exists()

Return whether the cached content exists.

Return type:

bool

Returns:

True if the content is cached, False otherwise.

locked()

Context manager that acquires an exclusive lock on this store.

Return type:

Generator[None]

Returns:

a context manager; the lock is held inside its with block.

read()

Read the cached content, or None if unavailable or corrupt.

Return type:

dict | None

Returns:

the cached content, or None.

remove()

Delete the cached content.

Return type:

None

write(content)

Persist content to the store.

Parameters:

content (dict) – interpreter metadata to cache.

Return type:

None

class python_discovery.DiskCache(root)

Bases: object

File-system based Python interpreter info cache (<root>/py_info/4/<sha256>.json).

Parameters:

root (Path) – root directory for the on-disk cache.

py_info(path)

Return the content store for the interpreter at path.

Parameters:

path (Path) – absolute path to a Python executable.

Return type:

ContentStore

Returns:

the content store for path.

py_info_clear()

Remove all cached interpreter information.

Return type:

None

class python_discovery.MarkerEnvironment

Bases: TypedDict

Environment markers of an interpreter, as defined by PEP 508.

Variables:
  • implementation_name – the implementation_name marker.

  • implementation_version – the implementation_version marker.

  • os_name – the os_name marker.

  • platform_machine – the platform_machine marker.

  • platform_release – the platform_release marker.

  • platform_system – the platform_system marker.

  • platform_version – the platform_version marker.

  • python_full_version – the python_full_version marker.

  • platform_python_implementation – the platform_python_implementation marker.

  • python_version – the python_version marker.

  • sys_platform – the sys_platform marker.

implementation_name: str
implementation_version: str
os_name: str
platform_machine: str
platform_python_implementation: str
platform_release: str
platform_system: str
platform_version: str
python_full_version: str
python_version: str
sys_platform: str
class python_discovery.PyInfoCache(*args, **kwargs)

Bases: Protocol

Cache interface for Python interpreter information.

py_info(path)

Return the content store for the interpreter at path.

Parameters:

path (Path) – absolute path to a Python executable.

Return type:

ContentStore

Returns:

the content store for path.

py_info_clear()

Remove all cached interpreter information.

Return type:

None

class python_discovery.PythonInfo

Bases: object

Contains information for a Python interpreter.

Variables:
  • platform – the platform name, as reported by sys.platform.

  • implementation – the implementation name, such as CPython.

  • pypy_version_info – the PyPy version tuple, empty for other implementations.

  • version_info – the interpreter version as a named tuple.

  • architecture – the pointer width in bits, 32 or 64.

  • sysconfig_platform – the platform string from sysconfig, or None.

  • version_nodot – the major.minor version without the dot.

  • version – the full version string from sys.version.

  • os – the operating system name, as reported by os.name.

  • free_threaded – whether the interpreter was built free-threaded.

  • debug_build – whether the interpreter was built with Py_DEBUG.

  • marker_environment – the PEP 508 marker environment of the interpreter.

  • prefix – the sys.prefix of the interpreter.

  • base_prefix – the sys.base_prefix of the interpreter.

  • real_prefix – the sys.real_prefix set by legacy virtualenv, or None.

  • base_exec_prefix – the sys.base_exec_prefix of the interpreter.

  • exec_prefix – the sys.exec_prefix of the interpreter.

  • executable – the sys.executable of the interpreter.

  • original_executable – the absolute path to the executable, without resolving symlinks.

  • system_executable – the system interpreter behind any virtualenv, or None.

  • has_venv – whether the venv module can be imported.

  • path – the sys.path of the interpreter.

  • file_system_encoding – the filesystem encoding, from sys.getfilesystemencoding().

  • stdout_encoding – the encoding of sys.stdout, or None.

  • sysconfig_scheme – the installation scheme behind sysconfig_paths, or None.

  • sysconfig_paths – the installation paths, keyed by sysconfig path name.

  • distutils_install – the distutils installation directories, empty when sysconfig supplies them.

  • sysconfig – the sysconfig build metadata, such as the makefile filename.

  • sysconfig_vars – the sysconfig config variables queried for this interpreter.

  • tcl_lib – the Tcl library path, or None.

  • tk_lib – the Tk library path, or None.

  • system_stdlib – the standard library path of the system interpreter.

  • system_stdlib_platform – the platform standard library path of the system interpreter.

  • max_size – the sys.maxsize of the interpreter.

architecture: int
base_exec_prefix: str | None
base_prefix: str | None
classmethod clear_cache(cache)

Clear all cached interpreter information from cache.

Parameters:

cache (PyInfoCache) – the cache store to clear.

Return type:

None

classmethod current(cache=None)

Locate the current host interpreter information.

Parameters:

cache (PyInfoCache | None) – interpreter metadata cache; when None results are not cached.

Return type:

PythonInfo

Returns:

the information about the running interpreter.

Raises:

RuntimeError – if the running interpreter cannot be queried.

classmethod current_system(cache=None)

Locate the current system interpreter information, resolving through any virtualenv layers.

Parameters:

cache (PyInfoCache | None) – interpreter metadata cache; when None results are not cached.

Return type:

PythonInfo

Returns:

the system interpreter behind any virtualenv layers.

Raises:

RuntimeError – if the system interpreter cannot be queried.

debug_build: bool
discover_exe(cache, prefix, *, exact=True, env=None)

Discover a matching Python executable under a given prefix directory.

Parameters:
  • cache (PyInfoCache) – interpreter metadata cache.

  • prefix (str) – directory prefix to search under.

  • exact (bool) – when True, require an exact version match.

  • env (Mapping[str, str] | None) – environment mapping; defaults to os.environ.

Return type:

PythonInfo

Returns:

the matching interpreter information.

Raises:

RuntimeError – if no matching interpreter is found.

distutils_install: dict[str, str]
exec_prefix: str | None
executable: str
file_system_encoding: str
free_threaded: bool
classmethod from_dict(data)

Reconstruct a PythonInfo from a plain dictionary.

Parameters:

data (dict[str, str | int | bool | None | tuple[int | str, ...] | list[str] | dict[str, str | int | None]]) – dictionary produced by to_dict().

Return type:

PythonInfo

Returns:

the interpreter information rebuilt from data.

Raises:

ValueError – if data lacks an annotated field.

classmethod from_exe(exe, cache=None, *, raise_on_error=True, ignore_cache=False, resolve_to_host=True, env=None)

Get the python information for a given executable path.

Parameters:
  • exe (str) – path to the Python executable.

  • cache (PyInfoCache | None) – interpreter metadata cache; when None results are not cached.

  • raise_on_error (bool) – raise on failure instead of returning None.

  • ignore_cache (bool) – bypass the cache and re-query the interpreter.

  • resolve_to_host (bool) – resolve through virtualenv layers to the system interpreter.

  • env (Mapping[str, str] | None) – environment mapping; defaults to os.environ.

Return type:

PythonInfo | None

Returns:

the interpreter information, or None when it cannot be queried.

classmethod from_json(payload)

Deserialize interpreter information from a JSON string.

Parameters:

payload (str) – JSON produced by to_json().

Return type:

PythonInfo

Returns:

the interpreter information decoded from payload.

has_venv: bool
implementation: str
install_path(key)

Return the relative installation path for a given installation scheme key.

Parameters:

key (str) – sysconfig installation scheme key (e.g. "scripts", "purelib").

Return type:

str

Returns:

the installation path relative to the prefix.

property is_old_virtualenv: bool

True if this interpreter runs inside an old-style virtualenv (has real_prefix).

property is_venv: bool

True if this interpreter runs inside a PEP 405 venv (has base_prefix).

property machine: str

The instruction set architecture (ISA) derived from sysconfig.get_platform().

marker_environment: MarkerEnvironment
max_size: int
original_executable: str
os: str
path: list[str]
platform: str
prefix: str | None
pypy_version_info: tuple[int, ...]
property python_name: str

The python executable name as pythonX.Y (e.g. python3.13).

real_prefix: str | None
classmethod resolve_to_system(cache, target, *, env=None)

Walk virtualenv/venv prefix chains to find the underlying system interpreter.

Parameters:
  • cache (PyInfoCache | None) – interpreter metadata cache; when None results are not cached.

  • target (PythonInfo) – the interpreter to resolve.

  • env (Mapping[str, str] | None) – environment mapping; defaults to os.environ.

Return type:

PythonInfo

Returns:

the system interpreter that target resolves to.

Raises:

RuntimeError – if the prefixes form a cycle.

satisfies(spec, *, impl_must_match)

Check if a given specification can be satisfied by this python interpreter instance.

Parameters:
  • spec (PythonSpec) – the specification to check against.

  • impl_must_match (bool) – when True, the implementation name must match exactly.

Return type:

bool

Returns:

True if this interpreter satisfies spec.

property spec: str

A specification string identifying this interpreter (e.g. CPython3.13.2-64-arm64).

stdout_encoding: str | None
sysconfig: dict[str, str | None]
sysconfig_path(key, config_var=None, sep='/')

Return the sysconfig install path for a scheme key, optionally substituting config variables.

Parameters:
  • key (str) – sysconfig path key (e.g. "purelib", "include").

  • config_var (dict[str, str | int | None] | None) – replacement mapping for sysconfig variables; when None uses the interpreter’s own values.

  • sep (str) – path separator to use in the result.

Return type:

str

Returns:

the path, or an empty string if key is unknown.

Raises:

ValueError – if the sysconfig pattern contains format specifiers.

sysconfig_paths: dict[str, str]
sysconfig_platform: str | None
sysconfig_scheme: str | None
sysconfig_vars: dict[str, str | int | None]
property system_exe: str

The executable of the system Python this interpreter is based on.

system_executable stays None until resolve_to_system() walks the prefix chain, so reading it forces every caller to narrow a value discovery has already settled. The fallback here matches what resolution itself writes when a prefix links back to its own interpreter.

property system_exec_prefix: str

The exec prefix of the system Python this interpreter is based on.

system_executable: str | None
property system_include: str

The path to the system include directory for C headers.

property system_prefix: str

The prefix of the system Python this interpreter is based on.

system_stdlib: str
system_stdlib_platform: str
tcl_lib: str | None
tk_lib: str | None
to_dict()

Convert this interpreter information to a plain dictionary.

Return type:

dict[str, str | int | bool | None | tuple[int | str, ...] | list[str] | dict[str, str | int | None]]

Returns:

the interpreter information as a dictionary.

to_json()

Serialize this interpreter information to a JSON string.

Return type:

str

Returns:

the JSON document.

version: str
version_info: VersionInfo
version_nodot: str | None
property version_release_str: str

The release version as major.minor string (e.g. 3.13).

property version_str: str

The full version as major.minor.micro string (e.g. 3.13.2).

class python_discovery.PythonSpec(str_spec, implementation, major, minor, micro, architecture, path, *, free_threaded=None, machine=None, debug=None, version_specifier=None)

Bases: object

Contains specification about a Python Interpreter.

Parameters:
  • str_spec (str) – the raw specification string as provided by the caller.

  • implementation (str | None) – interpreter implementation name (e.g. "cpython", "pypy"), or None for any.

  • major (int | None) – required major version, or None for any.

  • minor (int | None) – required minor version, or None for any.

  • micro (int | None) – required micro (patch) version, or None for any.

  • architecture (int | None) – required pointer-size bitness (32 or 64), or None for any.

  • path (str | None) – filesystem path to a specific interpreter, or None.

  • free_threaded (bool | None) – whether a free-threaded build is required, or None for any.

  • machine (str | None) – required ISA (e.g. "arm64"), or None for any.

  • debug (bool | None) – whether a debug (Py_DEBUG) build is required, or None for any.

  • version_specifier (SimpleSpecifierSet | None) – version specifier constraints, or None.

classmethod from_string_spec(string_spec)

Parse a string specification into a PythonSpec.

Parameters:

string_spec (str) –

an interpreter spec — an absolute path, a version string, an implementation prefix, or a version specifier.

Return type:

PythonSpec

Returns:

the parsed specification.

Raises:

ValueError – if the spec starts with a version specifier operator but does not parse as one.

generate_re(*, windows, all_implementations=False)

Generate a regular expression for matching interpreter filenames.

Parameters:
  • windows (bool) – if True, require a .exe suffix.

  • all_implementations (bool) – when True and the spec does not constrain the implementation, match every filename in KNOWN_IMPLEMENTATIONS instead of only python. A free-threaded or debug build the spec leaves open also matches its marked name, such as python3.13t or python3.13-dbg. Used by enumeration APIs.

Return type:

Pattern

Returns:

a compiled pattern matching the filenames the spec accepts.

property is_abs: bool

True if the spec refers to an absolute filesystem path.

satisfies(spec)

Check if this spec is compatible with the given spec (e.g. PEP-514 on Windows).

Parameters:

spec (PythonSpec) – the requirement to check against.

Return type:

bool

Returns:

True if this spec is compatible with spec.

class python_discovery.SimpleSpecifier(*, spec_str, operator, version_str, is_wildcard, wildcard_precision, version)

Bases: object

Simple PEP 440-like version specifier using only standard library.

Parameters:
  • spec_str (str) – the original specifier string (e.g. >=3.10).

  • operator (str) – the comparison operator (==, >=, <, etc.).

  • version_str (str) – the version portion of the specifier, without the operator.

  • is_wildcard (bool) – True if the specifier uses a wildcard suffix (.*).

  • wildcard_precision (int | None) – number of version components before the wildcard, or None.

  • version (SimpleVersion | None) – the parsed version, or None if parsing failed.

contains(version_str)

Check if a version string satisfies this specifier.

Parameters:

version_str (str) – the version string to test.

Return type:

bool

Returns:

True if version_str satisfies this specifier.

classmethod from_string(spec_str)

Parse a single PEP 440 specifier (e.g. >=3.10).

Parameters:

spec_str (str) – the specifier string to parse.

Return type:

SimpleSpecifier

Returns:

the parsed specifier.

Raises:

ValueError – if spec_str is not a valid specifier.

is_wildcard: bool
operator: str
spec_str: str
version: SimpleVersion | None
version_str: str
wildcard_precision: int | None
class python_discovery.SimpleSpecifierSet(*, specifiers_str, specifiers)

Bases: object

Simple PEP 440-like specifier set using only standard library.

Parameters:
  • specifiers_str (str) – the original comma-separated specifier string.

  • specifiers (tuple[SimpleSpecifier, ...]) – the parsed individual specifiers.

contains(version_str)

Check if a version satisfies all specifiers in the set.

Parameters:

version_str (str) – the version string to test.

Return type:

bool

Returns:

True if version_str satisfies every specifier.

classmethod from_string(specifiers_str='')

Parse a comma-separated PEP 440 specifier string (e.g. >=3.10,<4).

Parameters:

specifiers_str (str) – the specifier string to parse.

Return type:

SimpleSpecifierSet

Returns:

the parsed specifier set.

specifiers: tuple[SimpleSpecifier, ...]
specifiers_str: str
class python_discovery.SimpleVersion(*, version_str, major, minor, micro, pre_type, pre_num, release)

Bases: object

Simple PEP 440-like version parser using only standard library.

Parameters:
  • version_str (str) – the original version string.

  • major (int) – major version number.

  • minor (int) – minor version number.

  • micro (int) – micro (patch) version number.

  • pre_type (str | None) – pre-release label ("a", "b", or "rc"), or None.

  • pre_num (int | None) – pre-release sequence number, or None.

  • release (tuple[int, int, int]) – the (major, minor, micro) tuple.

classmethod from_string(version_str)

Parse a PEP 440 version string (e.g. 3.12.1).

Parameters:

version_str (str) – the version string to parse.

Return type:

SimpleVersion

Returns:

the parsed version.

Raises:

ValueError – if version_str is not a valid version.

major: int
micro: int
minor: int
pre_num: int | None
pre_type: str | None
release: tuple[int, int, int]
version_str: str
python_discovery.get_interpreter(key, try_first_with=None, cache=None, env=None, predicate=None)

Find a Python interpreter matching key.

Iterates over one or more specification strings and returns the first interpreter that satisfies the spec and passes the optional predicate.

Parameters:
  • key (str | Sequence[str]) –

    interpreter specification string(s) — an absolute path, a version (3.12), an implementation prefix (cpython3.12), or a version specifier (>=3.10). When a sequence is given each entry is tried in order.

  • try_first_with (Iterable[str] | None) – executables to probe before the normal discovery search. A relative path spec is checked first.

  • cache (PyInfoCache | None) – interpreter metadata cache; when None results are not cached.

  • env (Mapping[str, str] | None) – environment mapping for PATH and uv store lookup; defaults to os.environ.

  • predicate (Callable[[PythonInfo], bool] | None) – optional callback applied after an interpreter matches the spec. Return True to accept the interpreter, False to skip it and continue searching.

Return type:

PythonInfo | None

Returns:

the first matching interpreter, or None if no match is found.

python_discovery.iter_interpreters(key=None, try_first_with=None, cache=None, env=None, predicate=None)

Yield every interpreter on the system that satisfies key.

Iteration order is discovery order: try_first_with paths first, then the running interpreter, then PATH (left to right), then UV-managed installs. Results are deduplicated by the resolved real path of the underlying system interpreter, so symlinked aliases (/bin vs /usr/bin) and venvs that symlink to a base interpreter collapse to a single entry. Callers that want a different ordering should sort the result.

Parameters:
  • key (str | Sequence[str] | None) – interpreter specification — same syntax as get_interpreter(). None enumerates every Python implementation python-discovery knows about (see KNOWN_IMPLEMENTATIONS).

  • try_first_with (Iterable[str] | None) – executables to probe before the normal discovery search.

  • cache (PyInfoCache | None) – interpreter metadata cache; when None results are not cached. Strongly recommended for enumeration, which interrogates every candidate as a subprocess on a cold cache.

  • env (Mapping[str, str] | None) – environment mapping for PATH and uv store lookup; defaults to os.environ.

  • predicate (Callable[[PythonInfo], bool] | None) – optional filter applied after the spec match; return True to include the interpreter.

Yields:

each matching interpreter, in discovery order.

python_discovery.normalize_isa(isa)

Normalize an ISA (instruction set architecture) string to a canonical form.

Known aliases are mapped (e.g. amd64 → x86_64, aarch64 → arm64). Unrecognized values are lowercased and returned as-is.

Parameters:

isa (str) – the architecture string as the platform reports it.

Return type:

str

Returns:

the normalized architecture name.