]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.14] gh-153896: Deduplicate unhashable arguments in `typing.Literal` (GH-153914...
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Sun, 19 Jul 2026 07:56:06 +0000 (09:56 +0200)
committerGitHub <noreply@github.com>
Sun, 19 Jul 2026 07:56:06 +0000 (09:56 +0200)
gh-153896: Deduplicate unhashable arguments in `typing.Literal` (GH-153914)
(cherry picked from commit a53b5b126749133e50692fe0c3729f5580ee8500)

Co-authored-by: Massimiliano Bruni <massimiliano.bruni@icloud.com>
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 8786c1b4dfecda674db73876b5a0baf06a162ef6..57cc1db6141e3264c0aa9137b4ab4bebf8a70ad0 100644 (file)
@@ -2739,8 +2739,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 9308e0820f55cb69a47beddd9fa14dabbf5dc3ac..2b4389b2967d12885b8547fcaa79ae969ee25c47 100644 (file)
@@ -772,13 +772,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`.