Skip to content

Commit 61aa141

Browse files
miss-islingtonMaxinho96tomasr8
authored
[3.15] gh-153896: Deduplicate unhashable arguments in typing.Literal (GH-153914) (#153955)
gh-153896: Deduplicate unhashable arguments in `typing.Literal` (GH-153914) (cherry picked from commit a53b5b1) Co-authored-by: Massimiliano Bruni <massimiliano.bruni@icloud.com> Co-authored-by: Tomas R. <tomas.roun8@gmail.com>
1 parent becc0f6 commit 61aa141

3 files changed

Lines changed: 18 additions & 8 deletions

File tree

Lib/test/test_typing.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2796,8 +2796,14 @@ def test_args(self):
27962796
self.assertEqual(Literal[1, 2, 3].__args__, (1, 2, 3))
27972797
self.assertEqual(Literal[1, 2, 3, 3].__args__, (1, 2, 3))
27982798
self.assertEqual(Literal[1, Literal[2], Literal[3, 4]].__args__, (1, 2, 3, 4))
2799-
# Mutable arguments will not be deduplicated
2800-
self.assertEqual(Literal[[], []].__args__, ([], []))
2799+
# Unhashable arguments will be deduplicated too
2800+
self.assertEqual(Literal[[], []].__args__, ([],))
2801+
self.assertEqual(Literal[{"a": 1}, {"a": 1}].__args__, ({"a": 1},))
2802+
self.assertEqual(
2803+
Literal[1, {'a': 'b'}, 2, {'a': 'b'}, 3].__args__,
2804+
(1, {'a': 'b'}, 2, 3),
2805+
)
2806+
self.assertEqual(Literal[{1}, {1}, {2}, {2}].__args__, ({1}, {2}))
28012807

28022808
def test_flatten(self):
28032809
l1 = Literal[Literal[1], Literal[2], Literal[3]]

Lib/typing.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -788,13 +788,16 @@ def open_helper(file: str, mode: MODE) -> str:
788788
# There is no '_type_check' call because arguments to Literal[...] are
789789
# values, not types.
790790
parameters = _flatten_literal_params(parameters)
791+
value_and_type_parameters = list(_value_and_type_iter(parameters))
792+
deduplicated_parameters = tuple(
793+
p
794+
for p, _ in _deduplicate(
795+
value_and_type_parameters,
796+
unhashable_fallback=True,
797+
)
798+
)
791799

792-
try:
793-
parameters = tuple(p for p, _ in _deduplicate(list(_value_and_type_iter(parameters))))
794-
except TypeError: # unhashable parameters
795-
pass
796-
797-
return _LiteralGenericAlias(self, parameters)
800+
return _LiteralGenericAlias(self, deduplicated_parameters)
798801

799802

800803
@_SpecialForm
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Deduplicate unhashable args in :data:`typing.Literal`.

0 commit comments

Comments
 (0)