]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-42345: Fix hash implementation of typing.Literal (GH-23383)
authorYurii Karabas <1998uriyyo@gmail.com>
Thu, 19 Nov 2020 16:17:38 +0000 (18:17 +0200)
committerGitHub <noreply@github.com>
Thu, 19 Nov 2020 16:17:38 +0000 (08:17 -0800)
Fix hash implementation of `typing.Literal`.

Update docs regarding `typing.Litaral` caching.

Base implementation was done in PR #23294.

Doc/library/typing.rst
Lib/test/test_typing.py
Lib/typing.py

index a8de984a5ce41b63cd1bdb945bde9d6c1b1a9877..5b66e3c2c5b63955e053bb0d947553af1431a94c 100644 (file)
@@ -1706,9 +1706,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::
 
index 7deba0d71b7c4fab5c78405a440785b78ad2fbad..8ffc7f40cebdd275f49095120d9745c6e699cdd8 100644 (file)
@@ -569,6 +569,11 @@ class LiteralTests(BaseTestCase):
         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))
index d310b3dd5820dcbd1271fb0a7fa17f0dc04d3969..46c54c406992f748fa4b61ecfa75aea07a7400b6 100644 (file)
@@ -981,7 +981,7 @@ class _LiteralGenericAlias(_GenericAlias, _root=True):
         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: