Skip to content

Commit c689b93

Browse files
committed
Improve sorting logic
1 parent f200216 commit c689b93

File tree

1 file changed

+9
-11
lines changed

1 file changed

+9
-11
lines changed

src/pip/_internal/resolution/resolvelib/found_candidates.py

+9-11
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
1-
import functools
21
import itertools
2+
import operator
33

44
from pip._vendor.six.moves import collections_abc # type: ignore
55

66
from pip._internal.utils.compat import lru_cache
77
from pip._internal.utils.typing import MYPY_CHECK_RUNNING
88

99
if MYPY_CHECK_RUNNING:
10-
from typing import Any, Callable, Iterator, Optional, Set
10+
from typing import Callable, Iterator, Optional, Set
1111

1212
from pip._vendor.packaging.version import _BaseVersion
1313

@@ -24,11 +24,6 @@ def _deduplicated_by_version(candidates):
2424
yield candidate
2525

2626

27-
def _replaces_sort_key(installed, candidate):
28-
# type: (Candidate, Candidate) -> Any
29-
return (candidate.version, candidate is installed)
30-
31-
3227
def _insert_installed(installed, others):
3328
# type: (Candidate, Iterator[Candidate]) -> Iterator[Candidate]
3429
"""Iterator for ``FoundCandidates``.
@@ -37,12 +32,15 @@ def _insert_installed(installed, others):
3732
already-installed package. Candidates from index are returned in their
3833
normal ordering, except replaced when the version is already installed.
3934
40-
The sort key prefers the installed candidate over candidates of the same
41-
version from the index, so it is chosen on de-duplication.
35+
Since candidates from index are already sorted by reverse version order,
36+
`sorted()` here would keep the ordering mostly intact, only shuffling the
37+
already-installed candidate into the correct position. We put the already-
38+
installed candidate in front of those from the index, so it's put in front
39+
after sorting due to Python sorting's stableness guarentee.
4240
"""
4341
candidates = sorted(
44-
itertools.chain(others, [installed]),
45-
key=functools.partial(_replaces_sort_key, installed),
42+
itertools.chain([installed], others),
43+
key=operator.attrgetter("version"),
4644
reverse=True,
4745
)
4846
return iter(candidates)

0 commit comments

Comments
 (0)