Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vendor resolvelib 1.1.0 #13001

Merged
merged 6 commits into from
Feb 21, 2025
Merged
Changes from 5 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
2 changes: 0 additions & 2 deletions docs/html/topics/more-dependency-resolution.md
Original file line number Diff line number Diff line change
@@ -160,8 +160,6 @@ follows:
explicit URL.
* If equal, prefer if any requirement is "pinned", i.e. contains
operator ``===`` or ``==``.
* If equal, calculate an approximate "depth" and resolve requirements
closer to the user-specified requirements first.
* Order user-specified requirements by the order they are specified.
* If equal, prefers "non-free" requirements, i.e. contains at least one
operator, such as ``>=`` or ``<``.
5 changes: 5 additions & 0 deletions news/13001.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Resolvelib 1.1.0 fixes a known issue where pip would report a
ResolutionImpossible error even though there is a valid solution.
However, the performance of some very complex dependency resolutions
that previously resolved may be slower or result in a ResolutionTooDeep
error.
1 change: 1 addition & 0 deletions news/resolvelib.vendor.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Upgrade resolvelib to 1.1.0.
2 changes: 1 addition & 1 deletion src/pip/_internal/resolution/resolvelib/factory.py
Original file line number Diff line number Diff line change
@@ -748,7 +748,7 @@ def get_installation_error(
# The simplest case is when we have *one* cause that can't be
# satisfied. We just report that case.
if len(e.causes) == 1:
req, parent = e.causes[0]
req, parent = next(iter(e.causes))
if req.name not in constraints:
return self._report_single_requirement_conflict(req, parent)

24 changes: 0 additions & 24 deletions src/pip/_internal/resolution/resolvelib/provider.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import collections
import math
from functools import lru_cache
from typing import (
@@ -100,7 +99,6 @@ def __init__(
self._ignore_dependencies = ignore_dependencies
self._upgrade_strategy = upgrade_strategy
self._user_requested = user_requested
self._known_depths: Dict[str, float] = collections.defaultdict(lambda: math.inf)

def identify(self, requirement_or_candidate: Union[Requirement, Candidate]) -> str:
return requirement_or_candidate.name
@@ -124,10 +122,6 @@ def get_preference(
explicit URL.
* If equal, prefer if any requirement is "pinned", i.e. contains
operator ``===`` or ``==``.
* If equal, calculate an approximate "depth" and resolve requirements
closer to the user-specified requirements first. If the depth cannot
by determined (eg: due to no matching parents), it is considered
infinite.
* Order user-specified requirements by the order they are specified.
* If equal, prefers "non-free" requirements, i.e. contains at least one
operator, such as ``>=`` or ``<``.
@@ -157,23 +151,6 @@ def get_preference(
direct = candidate is not None
pinned = any(op[:2] == "==" for op in operators)
unfree = bool(operators)

try:
requested_order: Union[int, float] = self._user_requested[identifier]
except KeyError:
requested_order = math.inf
if has_information:
parent_depths = (
self._known_depths[parent.name] if parent is not None else 0.0
for _, parent in information[identifier]
)
inferred_depth = min(d for d in parent_depths) + 1.0
else:
inferred_depth = math.inf
else:
inferred_depth = 1.0
self._known_depths[identifier] = inferred_depth

requested_order = self._user_requested.get(identifier, math.inf)

# Requires-Python has only one candidate and the check is basically
@@ -190,7 +167,6 @@ def get_preference(
not direct,
not pinned,
not backtrack_cause,
inferred_depth,
requested_order,
not unfree,
identifier,
10 changes: 6 additions & 4 deletions src/pip/_internal/resolution/resolvelib/reporter.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from collections import defaultdict
from logging import getLogger
from typing import Any, DefaultDict
from typing import Any, DefaultDict, Optional

from pip._vendor.resolvelib.reporters import BaseReporter

@@ -9,7 +9,7 @@
logger = getLogger(__name__)


class PipReporter(BaseReporter):
class PipReporter(BaseReporter[Requirement, Candidate, str]):
def __init__(self) -> None:
self.reject_count_by_package: DefaultDict[str, int] = defaultdict(int)

@@ -55,7 +55,7 @@ def rejecting_candidate(self, criterion: Any, candidate: Candidate) -> None:
logger.debug(msg)


class PipDebuggingReporter(BaseReporter):
class PipDebuggingReporter(BaseReporter[Requirement, Candidate, str]):
"""A reporter that does an info log for every event it sees."""

def starting(self) -> None:
@@ -71,7 +71,9 @@ def ending_round(self, index: int, state: Any) -> None:
def ending(self, state: Any) -> None:
logger.info("Reporter.ending(%r)", state)

def adding_requirement(self, requirement: Requirement, parent: Candidate) -> None:
def adding_requirement(
self, requirement: Requirement, parent: Optional[Candidate]
) -> None:
logger.info("Reporter.adding_requirement(%r, %r)", requirement, parent)

def rejecting_candidate(self, criterion: Any, candidate: Candidate) -> None:
2 changes: 1 addition & 1 deletion src/pip/_internal/resolution/resolvelib/resolver.py
Original file line number Diff line number Diff line change
@@ -82,7 +82,7 @@ def resolve(
user_requested=collected.user_requested,
)
if "PIP_RESOLVER_DEBUG" in os.environ:
reporter: BaseReporter = PipDebuggingReporter()
reporter: BaseReporter[Requirement, Candidate, str] = PipDebuggingReporter()
else:
reporter = PipReporter()
resolver: RLResolver[Requirement, Candidate, str] = RLResolver(
5 changes: 3 additions & 2 deletions src/pip/_vendor/resolvelib/__init__.py
Original file line number Diff line number Diff line change
@@ -11,12 +11,13 @@
"ResolutionTooDeep",
]

__version__ = "1.0.1"
__version__ = "1.1.0"


from .providers import AbstractProvider, AbstractResolver
from .providers import AbstractProvider
from .reporters import BaseReporter
from .resolvers import (
AbstractResolver,
InconsistentCandidate,
RequirementsConflicted,
ResolutionError,
11 changes: 0 additions & 11 deletions src/pip/_vendor/resolvelib/__init__.pyi

This file was deleted.

Empty file.
6 changes: 0 additions & 6 deletions src/pip/_vendor/resolvelib/compat/collections_abc.py

This file was deleted.

1 change: 0 additions & 1 deletion src/pip/_vendor/resolvelib/compat/collections_abc.pyi

This file was deleted.

143 changes: 103 additions & 40 deletions src/pip/_vendor/resolvelib/providers.py
Original file line number Diff line number Diff line change
@@ -1,39 +1,68 @@
class AbstractProvider(object):
from __future__ import annotations

from typing import (
TYPE_CHECKING,
Generic,
Iterable,
Iterator,
Mapping,
Sequence,
)

from .structs import CT, KT, RT, Matches, RequirementInformation

if TYPE_CHECKING:
from typing import Any, Protocol

class Preference(Protocol):
def __lt__(self, __other: Any) -> bool: ...


class AbstractProvider(Generic[RT, CT, KT]):
"""Delegate class to provide the required interface for the resolver."""

def identify(self, requirement_or_candidate):
"""Given a requirement, return an identifier for it.
def identify(self, requirement_or_candidate: RT | CT) -> KT:
"""Given a requirement or candidate, return an identifier for it.
This is used to identify a requirement, e.g. whether two requirements
should have their specifier parts merged.
This is used to identify, e.g. whether two requirements
should have their specifier parts merged or a candidate matches a
requirement via ``find_matches()``.
"""
raise NotImplementedError

def get_preference(
self,
identifier,
resolutions,
candidates,
information,
backtrack_causes,
):
identifier: KT,
resolutions: Mapping[KT, CT],
candidates: Mapping[KT, Iterator[CT]],
information: Mapping[KT, Iterator[RequirementInformation[RT, CT]]],
backtrack_causes: Sequence[RequirementInformation[RT, CT]],
) -> Preference:
"""Produce a sort key for given requirement based on preference.
As this is a sort key it will be called O(n) times per backtrack
step, where n is the number of `identifier`s, if you have a check
which is expensive in some sense. E.g. It needs to make O(n) checks
per call or takes significant wall clock time, consider using
`narrow_requirement_selection` to filter the `identifier`s, which
is applied before this sort key is called.
The preference is defined as "I think this requirement should be
resolved first". The lower the return value is, the more preferred
this group of arguments is.
:param identifier: An identifier as returned by ``identify()``. This
identifies the dependency matches which should be returned.
identifies the requirement being considered.
:param resolutions: Mapping of candidates currently pinned by the
resolver. Each key is an identifier, and the value is a candidate.
The candidate may conflict with requirements from ``information``.
:param candidates: Mapping of each dependency's possible candidates.
Each value is an iterator of candidates.
:param information: Mapping of requirement information of each package.
Each value is an iterator of *requirement information*.
:param backtrack_causes: Sequence of requirement information that were
the requirements that caused the resolver to most recently backtrack.
:param backtrack_causes: Sequence of *requirement information* that are
the requirements that caused the resolver to most recently
backtrack.
A *requirement information* instance is a named tuple with two members:
@@ -60,15 +89,21 @@ def get_preference(
"""
raise NotImplementedError

def find_matches(self, identifier, requirements, incompatibilities):
def find_matches(
self,
identifier: KT,
requirements: Mapping[KT, Iterator[RT]],
incompatibilities: Mapping[KT, Iterator[CT]],
) -> Matches[CT]:
"""Find all possible candidates that satisfy the given constraints.
:param identifier: An identifier as returned by ``identify()``. This
identifies the dependency matches of which should be returned.
:param identifier: An identifier as returned by ``identify()``. All
candidates returned by this method should produce the same
identifier.
:param requirements: A mapping of requirements that all returned
candidates must satisfy. Each key is an identifier, and the value
an iterator of requirements for that dependency.
:param incompatibilities: A mapping of known incompatibilities of
:param incompatibilities: A mapping of known incompatibile candidates of
each dependency. Each key is an identifier, and the value an
iterator of incompatibilities known to the resolver. All
incompatibilities *must* be excluded from the return value.
@@ -89,7 +124,7 @@ def find_matches(self, identifier, requirements, incompatibilities):
"""
raise NotImplementedError

def is_satisfied_by(self, requirement, candidate):
def is_satisfied_by(self, requirement: RT, candidate: CT) -> bool:
"""Whether the given requirement can be satisfied by a candidate.
The candidate is guaranteed to have been generated from the
@@ -100,34 +135,62 @@ def is_satisfied_by(self, requirement, candidate):
"""
raise NotImplementedError

def get_dependencies(self, candidate):
def get_dependencies(self, candidate: CT) -> Iterable[RT]:
"""Get dependencies of a candidate.
This should return a collection of requirements that `candidate`
specifies as its dependencies.
"""
raise NotImplementedError

def narrow_requirement_selection(
self,
identifiers: Iterable[KT],
resolutions: Mapping[KT, CT],
candidates: Mapping[KT, Iterator[CT]],
information: Mapping[KT, Iterator[RequirementInformation[RT, CT]]],
backtrack_causes: Sequence[RequirementInformation[RT, CT]],
) -> Iterable[KT]:
"""
An optional method to narrow the selection of requirements being
considered during resolution. This method is called O(1) time per
backtrack step.
:param identifiers: An iterable of `identifiers` as returned by
``identify()``. These identify all requirements currently being
considered.
:param resolutions: A mapping of candidates currently pinned by the
resolver. Each key is an identifier, and the value is a candidate
that may conflict with requirements from ``information``.
:param candidates: A mapping of each dependency's possible candidates.
Each value is an iterator of candidates.
:param information: A mapping of requirement information for each package.
Each value is an iterator of *requirement information*.
:param backtrack_causes: A sequence of *requirement information* that are
the requirements causing the resolver to most recently
backtrack.
class AbstractResolver(object):
"""The thing that performs the actual resolution work."""

base_exception = Exception

def __init__(self, provider, reporter):
self.provider = provider
self.reporter = reporter

def resolve(self, requirements, **kwargs):
"""Take a collection of constraints, spit out the resolution result.
This returns a representation of the final resolution state, with one
guarenteed attribute ``mapping`` that contains resolved candidates as
values. The keys are their respective identifiers.
:param requirements: A collection of constraints.
:param kwargs: Additional keyword arguments that subclasses may accept.
A *requirement information* instance is a named tuple with two members:
:raises: ``self.base_exception`` or its subclass.
* ``requirement`` specifies a requirement contributing to the current
list of candidates.
* ``parent`` specifies the candidate that provides (is depended on for)
the requirement, or ``None`` to indicate a root requirement.
Must return a non-empty subset of `identifiers`, with the default
implementation being to return `identifiers` unchanged. Those `identifiers`
will then be passed to the sort key `get_preference` to pick the most
prefered requirement to attempt to pin, unless `narrow_requirement_selection`
returns only 1 requirement, in which case that will be used without
calling the sort key `get_preference`.
This method is designed to be used by the provider to optimize the
dependency resolution, e.g. if a check cost is O(m) and it can be done
against all identifiers at once then filtering the requirement selection
here will cost O(m) but making it part of the sort key in `get_preference`
will cost O(m*n), where n is the number of `identifiers`.
Returns:
Iterable[KT]: A non-empty subset of `identifiers`.
"""
raise NotImplementedError
return identifiers
44 changes: 0 additions & 44 deletions src/pip/_vendor/resolvelib/providers.pyi

This file was deleted.

30 changes: 21 additions & 9 deletions src/pip/_vendor/resolvelib/reporters.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,36 @@
class BaseReporter(object):
from __future__ import annotations

from typing import TYPE_CHECKING, Collection, Generic

from .structs import CT, KT, RT, RequirementInformation, State

if TYPE_CHECKING:
from .resolvers import Criterion


class BaseReporter(Generic[RT, CT, KT]):
"""Delegate class to provider progress reporting for the resolver."""

def starting(self):
def starting(self) -> None:
"""Called before the resolution actually starts."""

def starting_round(self, index):
def starting_round(self, index: int) -> None:
"""Called before each round of resolution starts.
The index is zero-based.
"""

def ending_round(self, index, state):
def ending_round(self, index: int, state: State[RT, CT, KT]) -> None:
"""Called before each round of resolution ends.
This is NOT called if the resolution ends at this round. Use `ending`
if you want to report finalization. The index is zero-based.
"""

def ending(self, state):
def ending(self, state: State[RT, CT, KT]) -> None:
"""Called before the resolution ends successfully."""

def adding_requirement(self, requirement, parent):
def adding_requirement(self, requirement: RT, parent: CT | None) -> None:
"""Called when adding a new requirement into the resolve criteria.
:param requirement: The additional requirement to be applied to filter
@@ -30,14 +40,16 @@ def adding_requirement(self, requirement, parent):
requirements passed in from ``Resolver.resolve()``.
"""

def resolving_conflicts(self, causes):
def resolving_conflicts(
self, causes: Collection[RequirementInformation[RT, CT]]
) -> None:
"""Called when starting to attempt requirement conflict resolution.
:param causes: The information on the collision that caused the backtracking.
"""

def rejecting_candidate(self, criterion, candidate):
def rejecting_candidate(self, criterion: Criterion[RT, CT], candidate: CT) -> None:
"""Called when rejecting a candidate during backtracking."""

def pinning(self, candidate):
def pinning(self, candidate: CT) -> None:
"""Called when adding a candidate to the potential solution."""
11 changes: 0 additions & 11 deletions src/pip/_vendor/resolvelib/reporters.pyi

This file was deleted.

79 changes: 0 additions & 79 deletions src/pip/_vendor/resolvelib/resolvers.pyi

This file was deleted.

27 changes: 27 additions & 0 deletions src/pip/_vendor/resolvelib/resolvers/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from ..structs import RequirementInformation
from .abstract import AbstractResolver, Result
from .criterion import Criterion
from .exceptions import (
InconsistentCandidate,
RequirementsConflicted,
ResolutionError,
ResolutionImpossible,
ResolutionTooDeep,
ResolverException,
)
from .resolution import Resolution, Resolver

__all__ = [
"AbstractResolver",
"InconsistentCandidate",
"Resolver",
"Resolution",
"RequirementsConflicted",
"ResolutionError",
"ResolutionImpossible",
"ResolutionTooDeep",
"RequirementInformation",
"ResolverException",
"Result",
"Criterion",
]
47 changes: 47 additions & 0 deletions src/pip/_vendor/resolvelib/resolvers/abstract.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
from __future__ import annotations

import collections
from typing import TYPE_CHECKING, Any, Generic, Iterable, Mapping, NamedTuple

from ..structs import CT, KT, RT, DirectedGraph

if TYPE_CHECKING:
from ..providers import AbstractProvider
from ..reporters import BaseReporter
from .criterion import Criterion

class Result(NamedTuple, Generic[RT, CT, KT]):
mapping: Mapping[KT, CT]
graph: DirectedGraph[KT | None]
criteria: Mapping[KT, Criterion[RT, CT]]

else:
Result = collections.namedtuple("Result", ["mapping", "graph", "criteria"])


class AbstractResolver(Generic[RT, CT, KT]):
"""The thing that performs the actual resolution work."""

base_exception = Exception

def __init__(
self,
provider: AbstractProvider[RT, CT, KT],
reporter: BaseReporter[RT, CT, KT],
) -> None:
self.provider = provider
self.reporter = reporter

def resolve(self, requirements: Iterable[RT], **kwargs: Any) -> Result[RT, CT, KT]:
"""Take a collection of constraints, spit out the resolution result.
This returns a representation of the final resolution state, with one
guarenteed attribute ``mapping`` that contains resolved candidates as
values. The keys are their respective identifiers.
:param requirements: A collection of constraints.
:param kwargs: Additional keyword arguments that subclasses may accept.
:raises: ``self.base_exception`` or its subclass.
"""
raise NotImplementedError
48 changes: 48 additions & 0 deletions src/pip/_vendor/resolvelib/resolvers/criterion.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
from __future__ import annotations

from typing import Collection, Generic, Iterable, Iterator

from ..structs import CT, RT, RequirementInformation


class Criterion(Generic[RT, CT]):
"""Representation of possible resolution results of a package.
This holds three attributes:
* `information` is a collection of `RequirementInformation` pairs.
Each pair is a requirement contributing to this criterion, and the
candidate that provides the requirement.
* `incompatibilities` is a collection of all known not-to-work candidates
to exclude from consideration.
* `candidates` is a collection containing all possible candidates deducted
from the union of contributing requirements and known incompatibilities.
It should never be empty, except when the criterion is an attribute of a
raised `RequirementsConflicted` (in which case it is always empty).
.. note::
This class is intended to be externally immutable. **Do not** mutate
any of its attribute containers.
"""

def __init__(
self,
candidates: Iterable[CT],
information: Collection[RequirementInformation[RT, CT]],
incompatibilities: Collection[CT],
) -> None:
self.candidates = candidates
self.information = information
self.incompatibilities = incompatibilities

def __repr__(self) -> str:
requirements = ", ".join(
f"({req!r}, via={parent!r})" for req, parent in self.information
)
return f"Criterion({requirements})"

def iter_requirement(self) -> Iterator[RT]:
return (i.requirement for i in self.information)

def iter_parent(self) -> Iterator[CT | None]:
return (i.parent for i in self.information)
57 changes: 57 additions & 0 deletions src/pip/_vendor/resolvelib/resolvers/exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
from __future__ import annotations

from typing import TYPE_CHECKING, Collection, Generic

from ..structs import CT, RT, RequirementInformation

if TYPE_CHECKING:
from .criterion import Criterion


class ResolverException(Exception):
"""A base class for all exceptions raised by this module.
Exceptions derived by this class should all be handled in this module. Any
bubbling pass the resolver should be treated as a bug.
"""


class RequirementsConflicted(ResolverException, Generic[RT, CT]):
def __init__(self, criterion: Criterion[RT, CT]) -> None:
super().__init__(criterion)
self.criterion = criterion

def __str__(self) -> str:
return "Requirements conflict: {}".format(
", ".join(repr(r) for r in self.criterion.iter_requirement()),
)


class InconsistentCandidate(ResolverException, Generic[RT, CT]):
def __init__(self, candidate: CT, criterion: Criterion[RT, CT]):
super().__init__(candidate, criterion)
self.candidate = candidate
self.criterion = criterion

def __str__(self) -> str:
return "Provided candidate {!r} does not satisfy {}".format(
self.candidate,
", ".join(repr(r) for r in self.criterion.iter_requirement()),
)


class ResolutionError(ResolverException):
pass


class ResolutionImpossible(ResolutionError, Generic[RT, CT]):
def __init__(self, causes: Collection[RequirementInformation[RT, CT]]):
super().__init__(causes)
# causes is a list of RequirementInformation objects
self.causes = causes


class ResolutionTooDeep(ResolutionError):
def __init__(self, round_count: int) -> None:
super().__init__(round_count)
self.round_count = round_count

Large diffs are not rendered by default.

147 changes: 93 additions & 54 deletions src/pip/_vendor/resolvelib/structs.py
Original file line number Diff line number Diff line change
@@ -1,53 +1,92 @@
import itertools

from .compat import collections_abc

from __future__ import annotations

class DirectedGraph(object):
import itertools
from collections import namedtuple
from typing import (
TYPE_CHECKING,
Callable,
Generic,
Iterable,
Iterator,
Mapping,
NamedTuple,
Sequence,
TypeVar,
Union,
)

KT = TypeVar("KT") # Identifier.
RT = TypeVar("RT") # Requirement.
CT = TypeVar("CT") # Candidate.

Matches = Union[Iterable[CT], Callable[[], Iterable[CT]]]

if TYPE_CHECKING:
from .resolvers.criterion import Criterion

class RequirementInformation(NamedTuple, Generic[RT, CT]):
requirement: RT
parent: CT | None

class State(NamedTuple, Generic[RT, CT, KT]):
"""Resolution state in a round."""

mapping: dict[KT, CT]
criteria: dict[KT, Criterion[RT, CT]]
backtrack_causes: list[RequirementInformation[RT, CT]]

else:
RequirementInformation = namedtuple(
"RequirementInformation", ["requirement", "parent"]
)
State = namedtuple("State", ["mapping", "criteria", "backtrack_causes"])


class DirectedGraph(Generic[KT]):
"""A graph structure with directed edges."""

def __init__(self):
self._vertices = set()
self._forwards = {} # <key> -> Set[<key>]
self._backwards = {} # <key> -> Set[<key>]
def __init__(self) -> None:
self._vertices: set[KT] = set()
self._forwards: dict[KT, set[KT]] = {} # <key> -> Set[<key>]
self._backwards: dict[KT, set[KT]] = {} # <key> -> Set[<key>]

def __iter__(self):
def __iter__(self) -> Iterator[KT]:
return iter(self._vertices)

def __len__(self):
def __len__(self) -> int:
return len(self._vertices)

def __contains__(self, key):
def __contains__(self, key: KT) -> bool:
return key in self._vertices

def copy(self):
def copy(self) -> DirectedGraph[KT]:
"""Return a shallow copy of this graph."""
other = DirectedGraph()
other = type(self)()
other._vertices = set(self._vertices)
other._forwards = {k: set(v) for k, v in self._forwards.items()}
other._backwards = {k: set(v) for k, v in self._backwards.items()}
return other

def add(self, key):
def add(self, key: KT) -> None:
"""Add a new vertex to the graph."""
if key in self._vertices:
raise ValueError("vertex exists")
self._vertices.add(key)
self._forwards[key] = set()
self._backwards[key] = set()

def remove(self, key):
def remove(self, key: KT) -> None:
"""Remove a vertex from the graph, disconnecting all edges from/to it."""
self._vertices.remove(key)
for f in self._forwards.pop(key):
self._backwards[f].remove(key)
for t in self._backwards.pop(key):
self._forwards[t].remove(key)

def connected(self, f, t):
def connected(self, f: KT, t: KT) -> bool:
return f in self._backwards[t] and t in self._forwards[f]

def connect(self, f, t):
def connect(self, f: KT, t: KT) -> None:
"""Connect two existing vertices.
Nothing happens if the vertices are already connected.
@@ -57,56 +96,59 @@ def connect(self, f, t):
self._forwards[f].add(t)
self._backwards[t].add(f)

def iter_edges(self):
def iter_edges(self) -> Iterator[tuple[KT, KT]]:
for f, children in self._forwards.items():
for t in children:
yield f, t

def iter_children(self, key):
def iter_children(self, key: KT) -> Iterator[KT]:
return iter(self._forwards[key])

def iter_parents(self, key):
def iter_parents(self, key: KT) -> Iterator[KT]:
return iter(self._backwards[key])


class IteratorMapping(collections_abc.Mapping):
def __init__(self, mapping, accessor, appends=None):
class IteratorMapping(Mapping[KT, Iterator[CT]], Generic[RT, CT, KT]):
def __init__(
self,
mapping: Mapping[KT, RT],
accessor: Callable[[RT], Iterable[CT]],
appends: Mapping[KT, Iterable[CT]] | None = None,
) -> None:
self._mapping = mapping
self._accessor = accessor
self._appends = appends or {}
self._appends: Mapping[KT, Iterable[CT]] = appends or {}

def __repr__(self):
def __repr__(self) -> str:
return "IteratorMapping({!r}, {!r}, {!r})".format(
self._mapping,
self._accessor,
self._appends,
)

def __bool__(self):
def __bool__(self) -> bool:
return bool(self._mapping or self._appends)

__nonzero__ = __bool__ # XXX: Python 2.

def __contains__(self, key):
def __contains__(self, key: object) -> bool:
return key in self._mapping or key in self._appends

def __getitem__(self, k):
def __getitem__(self, k: KT) -> Iterator[CT]:
try:
v = self._mapping[k]
except KeyError:
return iter(self._appends[k])
return itertools.chain(self._accessor(v), self._appends.get(k, ()))

def __iter__(self):
def __iter__(self) -> Iterator[KT]:
more = (k for k in self._appends if k not in self._mapping)
return itertools.chain(self._mapping, more)

def __len__(self):
def __len__(self) -> int:
more = sum(1 for k in self._appends if k not in self._mapping)
return len(self._mapping) + more


class _FactoryIterableView(object):
class _FactoryIterableView(Iterable[RT]):
"""Wrap an iterator factory returned by `find_matches()`.
Calling `iter()` on this class would invoke the underlying iterator
@@ -115,56 +157,53 @@ class _FactoryIterableView(object):
built-in Python sequence types.
"""

def __init__(self, factory):
def __init__(self, factory: Callable[[], Iterable[RT]]) -> None:
self._factory = factory
self._iterable = None
self._iterable: Iterable[RT] | None = None

def __repr__(self):
return "{}({})".format(type(self).__name__, list(self))
def __repr__(self) -> str:
return f"{type(self).__name__}({list(self)})"

def __bool__(self):
def __bool__(self) -> bool:
try:
next(iter(self))
except StopIteration:
return False
return True

__nonzero__ = __bool__ # XXX: Python 2.

def __iter__(self):
iterable = (
self._factory() if self._iterable is None else self._iterable
)
def __iter__(self) -> Iterator[RT]:
iterable = self._factory() if self._iterable is None else self._iterable
self._iterable, current = itertools.tee(iterable)
return current


class _SequenceIterableView(object):
class _SequenceIterableView(Iterable[RT]):
"""Wrap an iterable returned by find_matches().
This is essentially just a proxy to the underlying sequence that provides
the same interface as `_FactoryIterableView`.
"""

def __init__(self, sequence):
def __init__(self, sequence: Sequence[RT]):
self._sequence = sequence

def __repr__(self):
return "{}({})".format(type(self).__name__, self._sequence)
def __repr__(self) -> str:
return f"{type(self).__name__}({self._sequence})"

def __bool__(self):
def __bool__(self) -> bool:
return bool(self._sequence)

__nonzero__ = __bool__ # XXX: Python 2.

def __iter__(self):
def __iter__(self) -> Iterator[RT]:
return iter(self._sequence)


def build_iter_view(matches):
def build_iter_view(matches: Matches[CT]) -> Iterable[CT]:
"""Build an iterable view from the value returned by `find_matches()`."""
if callable(matches):
return _FactoryIterableView(matches)
if not isinstance(matches, collections_abc.Sequence):
if not isinstance(matches, Sequence):
matches = list(matches)
return _SequenceIterableView(matches)


IterableView = Iterable
40 changes: 0 additions & 40 deletions src/pip/_vendor/resolvelib/structs.pyi

This file was deleted.

2 changes: 1 addition & 1 deletion src/pip/_vendor/vendor.txt
Original file line number Diff line number Diff line change
@@ -12,7 +12,7 @@ requests==2.32.3
rich==13.9.4
pygments==2.18.0
typing_extensions==4.12.2
resolvelib==1.0.1
resolvelib==1.1.0
setuptools==70.3.0
tomli==2.2.1
truststore==0.10.0
78 changes: 0 additions & 78 deletions tests/unit/resolution_resolvelib/test_provider.py

This file was deleted.