Skip to content

Commit 3a7402c

Browse files
committed
gh-153896: Deduplicate mutable args in Literal type
1 parent ff56462 commit 3a7402c

3 files changed

Lines changed: 15 additions & 6 deletions

File tree

Lib/test/test_typing.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2801,8 +2801,13 @@ def test_args(self):
28012801
self.assertEqual(Literal[1, 2, 3].__args__, (1, 2, 3))
28022802
self.assertEqual(Literal[1, 2, 3, 3].__args__, (1, 2, 3))
28032803
self.assertEqual(Literal[1, Literal[2], Literal[3, 4]].__args__, (1, 2, 3, 4))
2804-
# Mutable arguments will not be deduplicated
2805-
self.assertEqual(Literal[[], []].__args__, ([], []))
2804+
# Mutable arguments will also be deduplicated:
2805+
self.assertEqual(Literal[[], []].__args__, ([],))
2806+
self.assertEqual(
2807+
Literal[1, {'a': 'b'}, 2, {'a': 'b'}, 3].__args__,
2808+
(1, {'a': 'b'}, 2, 3),
2809+
)
2810+
self.assertEqual(Literal[{1}, {1}, {2}, {2}].__args__, ({1}, {2}))
28062811

28072812
def test_flatten(self):
28082813
l1 = Literal[Literal[1], Literal[2], Literal[3]]

Lib/typing.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -776,10 +776,13 @@ def open_helper(file: str, mode: MODE) -> str:
776776
# values, not types.
777777
parameters = _flatten_literal_params(parameters)
778778

779-
try:
780-
parameters = tuple(p for p, _ in _deduplicate(list(_value_and_type_iter(parameters))))
781-
except TypeError: # unhashable parameters
782-
pass
779+
parameters = tuple(
780+
p
781+
for p, _ in _deduplicate(
782+
list(_value_and_type_iter(parameters)),
783+
unhashable_fallback=True,
784+
)
785+
)
783786

784787
return _LiteralGenericAlias(self, parameters)
785788

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

0 commit comments

Comments
 (0)