]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-153896: Deduplicate unhashable arguments in `typing.Literal` (GH-153914)
authorMassimiliano Bruni <massimiliano.bruni@icloud.com>
Sat, 18 Jul 2026 13:16:03 +0000 (15:16 +0200)
committerGitHub <noreply@github.com>
Sat, 18 Jul 2026 13:16:03 +0000 (09:16 -0400)
Lib/test/test_typing.py
Lib/typing.py
Misc/NEWS.d/next/Library/2026-07-18-10-52-10.gh-issue-153896.87oevp.rst [new file with mode: 0644]

index 17574c7f03d8e1e5ba1070bad4ccc120e69111ea..c1f340230159db6619f05688cf921f85296bd924 100644 (file)
@@ -2801,8 +2801,14 @@ class LiteralTests(BaseTestCase):
         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, Literal[2], Literal[3, 4]].__args__, (1, 2, 3, 4))
-        # Mutable arguments will not be deduplicated
-        self.assertEqual(Literal[[], []].__args__, ([], []))
+        # Unhashable arguments will be deduplicated too
+        self.assertEqual(Literal[[], []].__args__, ([],))
+        self.assertEqual(Literal[{"a": 1}, {"a": 1}].__args__, ({"a": 1},))
+        self.assertEqual(
+            Literal[1, {'a': 'b'}, 2, {'a': 'b'}, 3].__args__,
+            (1, {'a': 'b'}, 2, 3),
+        )
+        self.assertEqual(Literal[{1}, {1}, {2}, {2}].__args__, ({1}, {2}))
 
     def test_flatten(self):
         l1 = Literal[Literal[1], Literal[2], Literal[3]]
index 933336ff4cf37e2a618cda8e32e60caf69eb2a05..054420865d7fb50ce15286cef23471c0b1c636f0 100644 (file)
@@ -775,13 +775,16 @@ def Literal(self, *parameters):
     # There is no '_type_check' call because arguments to Literal[...] are
     # values, not types.
     parameters = _flatten_literal_params(parameters)
+    value_and_type_parameters = list(_value_and_type_iter(parameters))
+    deduplicated_parameters = tuple(
+        p
+        for p, _ in _deduplicate(
+            value_and_type_parameters,
+            unhashable_fallback=True,
+        )
+    )
 
-    try:
-        parameters = tuple(p for p, _ in _deduplicate(list(_value_and_type_iter(parameters))))
-    except TypeError:  # unhashable parameters
-        pass
-
-    return _LiteralGenericAlias(self, parameters)
+    return _LiteralGenericAlias(self, deduplicated_parameters)
 
 
 @_SpecialForm
diff --git a/Misc/NEWS.d/next/Library/2026-07-18-10-52-10.gh-issue-153896.87oevp.rst b/Misc/NEWS.d/next/Library/2026-07-18-10-52-10.gh-issue-153896.87oevp.rst
new file mode 100644 (file)
index 0000000..217a3d3
--- /dev/null
@@ -0,0 +1 @@
+Deduplicate unhashable args in :data:`typing.Literal`.