Skip to content

Commit 9755c8b

Browse files
authored
[builtins] Narrow tuple.__hash__ to forbid unhashable entries in the tuple (#15852)
1 parent 2e006bb commit 9755c8b

2 files changed

Lines changed: 18 additions & 4 deletions

File tree

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,27 @@
11
from __future__ import annotations
22

3-
from typing import Tuple
3+
import sys
4+
from typing import Any
45
from typing_extensions import assert_type
56

67

78
# Empty tuples, see #8275
8-
class TupleSub(Tuple[int, ...]):
9+
class TupleSub(tuple[int, ...]):
910
pass
1011

1112

1213
assert_type(TupleSub(), TupleSub)
1314
assert_type(TupleSub([1, 2, 3]), TupleSub)
15+
16+
# Hashability shenanigans, see #15852
17+
t: tuple[int, int] = (1, 3)
18+
hash(t)
19+
u: tuple[int, ...] = tuple(b"spam")
20+
hash(u)
21+
v: tuple[str] = ("",)
22+
hash(v)
23+
w: tuple[()] = ()
24+
hash(w)
25+
hash(tuple(sys.platform))
26+
x: tuple[Any, Any] = ((), ())
27+
hash(x)

‎stdlib/builtins.pyi‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ from _typeshed import (
3030
SupportsRichComparisonT,
3131
SupportsWrite,
3232
)
33-
from collections.abc import Awaitable, Callable, Iterable, Iterator, MutableSet, Set as AbstractSet, Sized
33+
from collections.abc import Awaitable, Callable, Hashable, Iterable, Iterator, MutableSet, Set as AbstractSet, Sized
3434
from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper
3535
from os import PathLike
3636
from types import CellType, CodeType, EllipsisType, GenericAlias, NotImplementedType, TracebackType, UnionType
@@ -1163,7 +1163,7 @@ class tuple(Sequence[_T_co]):
11631163
def __gt__(self, value: tuple[_T_co, ...], /) -> bool: ...
11641164
def __ge__(self, value: tuple[_T_co, ...], /) -> bool: ...
11651165
def __eq__(self, value: object, /) -> bool: ...
1166-
def __hash__(self) -> int: ...
1166+
def __hash__(self: tuple[Hashable, ...]) -> int: ...
11671167

11681168
@overload
11691169
def __add__(self, value: tuple[_T_co, ...], /) -> tuple[_T_co, ...]: ...

0 commit comments

Comments
 (0)