Skip to content

Commit ee21208

Browse files
authored
[heapq] Use overloads to prevent unsound uses (#15669)
1 parent d9814c0 commit ee21208

2 files changed

Lines changed: 19 additions & 9 deletions

File tree

stdlib/_heapq.pyi

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ from typing import Final
44

55
__about__: Final[str]
66

7-
def heapify(heap: list[_T], /) -> None: ...
7+
def heapify(heap: list[_T], /) -> None: ... # To work around the fact that list is invariant
88
def heappop(heap: list[_T], /) -> _T: ...
99
def heappush(heap: list[_T], item: _T, /) -> None: ...
1010
def heappushpop(heap: list[_T], item: _T, /) -> _T: ...

stdlib/heapq.pyi

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import sys
22
from _heapq import *
3-
from _typeshed import SupportsRichComparison
3+
from _typeshed import SupportsRichComparison, SupportsRichComparisonT as _T
44
from collections.abc import Callable, Generator, Iterable
5-
from typing import Any, Final, TypeVar
5+
from typing import Final, TypeVar, overload
66

77
__all__ = ["heappush", "heappop", "heapify", "heapreplace", "merge", "nlargest", "nsmallest", "heappushpop"]
88

@@ -14,9 +14,19 @@ _S = TypeVar("_S")
1414

1515
__about__: Final[str]
1616

17-
def merge(
18-
*iterables: Iterable[_S], key: Callable[[_S], SupportsRichComparison] | None = None, reverse: bool = False
19-
) -> Generator[_S]: ...
20-
def nlargest(n: int, iterable: Iterable[_S], key: Callable[[_S], SupportsRichComparison] | None = None) -> list[_S]: ...
21-
def nsmallest(n: int, iterable: Iterable[_S], key: Callable[[_S], SupportsRichComparison] | None = None) -> list[_S]: ...
22-
def _heapify_max(heap: list[Any], /) -> None: ... # undocumented
17+
@overload
18+
def merge(*iterables: Iterable[_S], key: Callable[[_S], SupportsRichComparison], reverse: bool = False) -> Generator[_S]: ...
19+
@overload
20+
def merge(*iterables: Iterable[_T], key: None = None, reverse: bool = False) -> Generator[_T]: ...
21+
22+
@overload
23+
def nlargest(n: int, iterable: Iterable[_S], key: Callable[[_S], SupportsRichComparison]) -> list[_S]: ...
24+
@overload
25+
def nlargest(n: int, iterable: Iterable[_T], key: None = None) -> list[_T]: ...
26+
27+
@overload
28+
def nsmallest(n: int, iterable: Iterable[_S], key: Callable[[_S], SupportsRichComparison]) -> list[_S]: ...
29+
@overload
30+
def nsmallest(n: int, iterable: Iterable[_T], key: None = None) -> list[_T]: ...
31+
32+
def _heapify_max(heap: list[SupportsRichComparison], /) -> None: ... # undocumented

0 commit comments

Comments
 (0)