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.
This commit is contained in:
parent
b437aa83f9
commit
1b54077ff6
|
@ -1706,9 +1706,9 @@ Introspection helpers
|
||||||
For a typing object of the form ``X[Y, Z, ...]`` these functions return
|
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
|
``X`` and ``(Y, Z, ...)``. If ``X`` is a generic alias for a builtin or
|
||||||
:mod:`collections` class, it gets normalized to the original class.
|
:mod:`collections` class, it gets normalized to the original class.
|
||||||
If ``X`` is a :class:`Union` contained in another generic type,
|
If ``X`` is a :class:`Union` or :class:`Literal` contained in another
|
||||||
the order of ``(Y, Z, ...)`` may be different from the order of
|
generic type, the order of ``(Y, Z, ...)`` may be different from the order
|
||||||
the original arguments ``[Y, Z, ...]`` due to type caching.
|
of the original arguments ``[Y, Z, ...]`` due to type caching.
|
||||||
For unsupported objects return ``None`` and ``()`` correspondingly.
|
For unsupported objects return ``None`` and ``()`` correspondingly.
|
||||||
Examples::
|
Examples::
|
||||||
|
|
||||||
|
|
|
@ -569,6 +569,11 @@ class LiteralTests(BaseTestCase):
|
||||||
self.assertEqual(Literal[1, 2], Literal[2, 1])
|
self.assertEqual(Literal[1, 2], Literal[2, 1])
|
||||||
self.assertEqual(Literal[1, 2, 3], Literal[1, 2, 3, 3])
|
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):
|
def test_args(self):
|
||||||
self.assertEqual(Literal[1, 2, 3].__args__, (1, 2, 3))
|
self.assertEqual(Literal[1, 2, 3].__args__, (1, 2, 3))
|
||||||
self.assertEqual(Literal[1, 2, 3, 3].__args__, (1, 2, 3))
|
self.assertEqual(Literal[1, 2, 3, 3].__args__, (1, 2, 3))
|
||||||
|
|
|
@ -981,7 +981,7 @@ class _LiteralGenericAlias(_GenericAlias, _root=True):
|
||||||
return set(_value_and_type_iter(self.__args__)) == set(_value_and_type_iter(other.__args__))
|
return set(_value_and_type_iter(self.__args__)) == set(_value_and_type_iter(other.__args__))
|
||||||
|
|
||||||
def __hash__(self):
|
def __hash__(self):
|
||||||
return hash(tuple(_value_and_type_iter(self.__args__)))
|
return hash(frozenset(_value_and_type_iter(self.__args__)))
|
||||||
|
|
||||||
|
|
||||||
class Generic:
|
class Generic:
|
||||||
|
|
Loading…
Reference in New Issue