Skip to content

Add an API for getting *all* interpreters #65

@Jackenmen

Description

@Jackenmen

Right now, there's no good way of getting a list of all interpreters in the system. This can be necessary if one wants certain interpreters to be preferred over others (e.g. search for interpreter 3.10-3.14 range, preferring newer versions over older). Also, to make it more convenient for the user, one might want to provide the user with a list of the discovered interpreters that they can choose from.

I feel I should note that it is possible to implement this today with the available public APIs, just in a somewhat hacky way, using predicate callable to populate the list of interpreters:

import os
from typing import Literal

from packaging.specifiers import SpecifierSet
from packaging.version import Version
from python_discovery import PythonInfo, get_interpreter


def get_available_interpreters(requires_python: SpecifierSet) -> list[tuple[str, Version, PythonInfo]]:
    interpreters = {}

    def _append_interpreter(info: PythonInfo) -> Literal[False]:
        version = Version(info.version_str)
        if version in requires_python:
            # realpath call is needed because get_interpreter lists
            # /usr/bin and /bin as separate even though they're the same path
            interpreters[os.path.realpath(info.executable)] = info
        return False

    get_interpreter("cpython", predicate=_append_interpreter)

    ret = [(key, *value) for key, value in interpreters.items()]
    ret.sort(key=itemgetter(1), reverse=True)
    return ret

Nonetheless, I figured it's probably worth making an issue for in case this is something you're interested in explicitly supporting.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions