Skip to content

Commit

Permalink
bpo-42345: Fix hash implementation of typing.Literal (GH-23383)
Browse files Browse the repository at this point in the history
Fix hash implementation of `typing.Literal`.

Update docs regarding `typing.Litaral` caching.

Base implementation was done in PR GH-23294.
(cherry picked from commit 1b54077)

Co-authored-by: Yurii Karabas <1998uriyyo@gmail.com>
  • Loading branch information
miss-islington and uriyyo committed Nov 19, 2020
1 parent 87c87b5 commit 2acd9d0
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 4 deletions.
6 changes: 3 additions & 3 deletions Doc/library/typing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1687,9 +1687,9 @@ Introspection helpers
For a typing object of the form ``X[Y, Z, ...]`` these functions return
``X`` and ``(Y, Z, ...)``. If ``X`` is a generic alias for a builtin or
:mod:`collections` class, it gets normalized to the original class.
If ``X`` is a :class:`Union` contained in another generic type,
the order of ``(Y, Z, ...)`` may be different from the order of
the original arguments ``[Y, Z, ...]`` due to type caching.
If ``X`` is a :class:`Union` or :class:`Literal` contained in another
generic type, the order of ``(Y, Z, ...)`` may be different from the order
of the original arguments ``[Y, Z, ...]`` due to type caching.
For unsupported objects return ``None`` and ``()`` correspondingly.
Examples::

Expand Down
5 changes: 5 additions & 0 deletions Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -573,6 +573,11 @@ def test_equal(self):
self.assertEqual(Literal[1, 2], Literal[2, 1])
self.assertEqual(Literal[1, 2, 3], Literal[1, 2, 3, 3])

def test_hash(self):
self.assertEqual(hash(Literal[1]), hash(Literal[1]))
self.assertEqual(hash(Literal[1, 2]), hash(Literal[2, 1]))
self.assertEqual(hash(Literal[1, 2, 3]), hash(Literal[1, 2, 3, 3]))

def test_args(self):
self.assertEqual(Literal[1, 2, 3].__args__, (1, 2, 3))
self.assertEqual(Literal[1, 2, 3, 3].__args__, (1, 2, 3))
Expand Down
2 changes: 1 addition & 1 deletion Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -932,7 +932,7 @@ def __eq__(self, other):
return set(_value_and_type_iter(self.__args__)) == set(_value_and_type_iter(other.__args__))

def __hash__(self):
return hash(tuple(_value_and_type_iter(self.__args__)))
return hash(frozenset(_value_and_type_iter(self.__args__)))


class Generic:
Expand Down

0 comments on commit 2acd9d0

Please sign in to comment.