Skip to content

Commit 1b54077

Browse files
authored
bpo-42345: Fix hash implementation of typing.Literal (GH-23383)
Fix hash implementation of `typing.Literal`. Update docs regarding `typing.Litaral` caching. Base implementation was done in PR #23294.
1 parent b437aa8 commit 1b54077

File tree

3 files changed

+9
-4
lines changed

3 files changed

+9
-4
lines changed

Doc/library/typing.rst

+3-3
Original file line numberDiff line numberDiff line change
@@ -1706,9 +1706,9 @@ Introspection helpers
17061706
For a typing object of the form ``X[Y, Z, ...]`` these functions return
17071707
``X`` and ``(Y, Z, ...)``. If ``X`` is a generic alias for a builtin or
17081708
:mod:`collections` class, it gets normalized to the original class.
1709-
If ``X`` is a :class:`Union` contained in another generic type,
1710-
the order of ``(Y, Z, ...)`` may be different from the order of
1711-
the original arguments ``[Y, Z, ...]`` due to type caching.
1709+
If ``X`` is a :class:`Union` or :class:`Literal` contained in another
1710+
generic type, the order of ``(Y, Z, ...)`` may be different from the order
1711+
of the original arguments ``[Y, Z, ...]`` due to type caching.
17121712
For unsupported objects return ``None`` and ``()`` correspondingly.
17131713
Examples::
17141714

Lib/test/test_typing.py

+5
Original file line numberDiff line numberDiff line change
@@ -569,6 +569,11 @@ def test_equal(self):
569569
self.assertEqual(Literal[1, 2], Literal[2, 1])
570570
self.assertEqual(Literal[1, 2, 3], Literal[1, 2, 3, 3])
571571

572+
def test_hash(self):
573+
self.assertEqual(hash(Literal[1]), hash(Literal[1]))
574+
self.assertEqual(hash(Literal[1, 2]), hash(Literal[2, 1]))
575+
self.assertEqual(hash(Literal[1, 2, 3]), hash(Literal[1, 2, 3, 3]))
576+
572577
def test_args(self):
573578
self.assertEqual(Literal[1, 2, 3].__args__, (1, 2, 3))
574579
self.assertEqual(Literal[1, 2, 3, 3].__args__, (1, 2, 3))

Lib/typing.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -981,7 +981,7 @@ def __eq__(self, other):
981981
return set(_value_and_type_iter(self.__args__)) == set(_value_and_type_iter(other.__args__))
982982

983983
def __hash__(self):
984-
return hash(tuple(_value_and_type_iter(self.__args__)))
984+
return hash(frozenset(_value_and_type_iter(self.__args__)))
985985

986986

987987
class Generic:

0 commit comments

Comments
 (0)