Skip to content

Commit 41a4d77

Browse files
simplify literal elimination
1 parent 6192ade commit 41a4d77

File tree

2 files changed

+10
-18
lines changed

2 files changed

+10
-18
lines changed

mypy/test/testtypes.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -635,6 +635,8 @@ def test_simplified_union_with_str_instance_literals(self) -> None:
635635
def test_simplified_union_with_mixed_str_literals(self) -> None:
636636
fx = self.fx
637637

638+
self.assert_simplified_union([fx.lit_str1, fx.lit_str1_inst], fx.lit_str1_inst)
639+
638640
self.assert_simplified_union(
639641
[fx.lit_str1, fx.lit_str2, fx.lit_str3_inst],
640642
UnionType([fx.lit_str1, fx.lit_str2, fx.lit_str3_inst]),

mypy/typeops.py

Lines changed: 8 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -611,25 +611,15 @@ def make_simplified_union(
611611
simplified_set = try_contracting_literals_in_union(simplified_set)
612612

613613
# Step 5: Combine Literals and Instances with LKVs, e.g. Literal[1]?, Literal[1] -> Literal[1]?
614-
new_items = []
615-
for item in simplified_set:
616-
if isinstance(item, LiteralType):
617-
# scan if there is an Instance with a last_known_value that matches
618-
for other in simplified_set:
619-
if (
620-
isinstance(other, Instance)
621-
and other.last_known_value is not None
622-
and item == other.last_known_value
623-
):
624-
# do not include item
625-
break
626-
else:
627-
new_items.append(item)
628-
else:
629-
# If the item is not a LiteralType, we can use it directly.
630-
new_items.append(item)
614+
proper_items: list[ProperType] = list(map(get_proper_type, simplified_set))
615+
last_known_values: list[LiteralType | None] = [
616+
p_t.last_known_value if isinstance(p_t, Instance) else None for p_t in proper_items
617+
]
618+
simplified_set = [
619+
item for item, p_t in zip(simplified_set, proper_items) if p_t not in last_known_values
620+
]
631621

632-
result = get_proper_type(UnionType.make_union(new_items, line, column))
622+
result = get_proper_type(UnionType.make_union(simplified_set, line, column))
633623

634624
nitems = len(items)
635625
if nitems > 1 and (

0 commit comments

Comments
 (0)