Skip to content

Commit 2acd9d0

Browse files
bpo-42345: Fix hash implementation of typing.Literal (pythonGH-23383)
Fix hash implementation of `typing.Literal`. Update docs regarding `typing.Litaral` caching. Base implementation was done in PR pythonGH-23294. (cherry picked from commit 1b54077) Co-authored-by: Yurii Karabas <1998uriyyo@gmail.com>
1 parent 87c87b5 commit 2acd9d0

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
@@ -1687,9 +1687,9 @@ Introspection helpers
16871687
For a typing object of the form ``X[Y, Z, ...]`` these functions return
16881688
``X`` and ``(Y, Z, ...)``. If ``X`` is a generic alias for a builtin or
16891689
:mod:`collections` class, it gets normalized to the original class.
1690-
If ``X`` is a :class:`Union` contained in another generic type,
1691-
the order of ``(Y, Z, ...)`` may be different from the order of
1692-
the original arguments ``[Y, Z, ...]`` due to type caching.
1690+
If ``X`` is a :class:`Union` or :class:`Literal` contained in another
1691+
generic type, the order of ``(Y, Z, ...)`` may be different from the order
1692+
of the original arguments ``[Y, Z, ...]`` due to type caching.
16931693
For unsupported objects return ``None`` and ``()`` correspondingly.
16941694
Examples::
16951695

Lib/test/test_typing.py

+5
Original file line numberDiff line numberDiff line change
@@ -573,6 +573,11 @@ def test_equal(self):
573573
self.assertEqual(Literal[1, 2], Literal[2, 1])
574574
self.assertEqual(Literal[1, 2, 3], Literal[1, 2, 3, 3])
575575

576+
def test_hash(self):
577+
self.assertEqual(hash(Literal[1]), hash(Literal[1]))
578+
self.assertEqual(hash(Literal[1, 2]), hash(Literal[2, 1]))
579+
self.assertEqual(hash(Literal[1, 2, 3]), hash(Literal[1, 2, 3, 3]))
580+
576581
def test_args(self):
577582
self.assertEqual(Literal[1, 2, 3].__args__, (1, 2, 3))
578583
self.assertEqual(Literal[1, 2, 3, 3].__args__, (1, 2, 3))

Lib/typing.py

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

934934
def __hash__(self):
935-
return hash(tuple(_value_and_type_iter(self.__args__)))
935+
return hash(frozenset(_value_and_type_iter(self.__args__)))
936936

937937

938938
class Generic:

0 commit comments

Comments
 (0)