Skip to content

Commit 3b87fdf

Browse files
committed
Speed up narrowing of large nominal unions
Reuse unchanged unrestricted instances when narrowing a union only removes existing members. Preserve recursive narrowing for introduced members, literal values, and restricted truthiness. Add regression coverage and a 300-member type-checking benchmark in check-unions.test.
1 parent 3420ef1 commit 3b87fdf

3 files changed

Lines changed: 514 additions & 14 deletions

File tree

‎mypy/meet.py‎

Lines changed: 43 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -126,21 +126,50 @@ def narrow_declared_type(declared: Type, narrowed: Type) -> Type:
126126
if declared == narrowed:
127127
return original_declared
128128
if isinstance(declared, UnionType):
129-
return make_simplified_union(
130-
[
131-
narrow_declared_type(x, narrowed)
132-
for x in declared.relevant_items()
133-
# This (ugly) special-casing is needed to support checking
134-
# branches like this:
135-
# x: Union[float, complex]
136-
# if isinstance(x, int):
137-
# ...
138-
if (
139-
is_overlapping_types(x, narrowed, ignore_promotions=True)
140-
or is_subtype(narrowed, x, ignore_promotions=False)
141-
)
142-
]
129+
narrowed_items = (
130+
{get_proper_type(item) for item in narrowed.relevant_items()}
131+
if isinstance(narrowed, UnionType)
132+
else set()
143133
)
134+
135+
def _is_overlapping_type(item: Type) -> bool:
136+
# Overlap alone is insufficient when numeric promotions are involved:
137+
# a declared float | complex may narrow to int even though the runtime
138+
# classes don't overlap.
139+
return is_overlapping_types(item, narrowed, ignore_promotions=True) or is_subtype(
140+
narrowed, item, ignore_promotions=False
141+
)
142+
143+
def _can_reuse_type(item: Type) -> bool:
144+
proper_item = get_proper_type(item)
145+
# Literal values and restricted truthiness still need recursive narrowing.
146+
return (
147+
isinstance(proper_item, Instance)
148+
and proper_item in narrowed_items
149+
and proper_item.last_known_value is None
150+
and proper_item.can_be_true
151+
and proper_item.can_be_false
152+
)
153+
154+
# Require exact membership, not subtyping. New members such as int
155+
# alongside float, or T[int] alongside T[Any], need recursive narrowing
156+
# to preserve the additional type information.
157+
if narrowed_items and narrowed_items.issubset(get_proper_types(declared.items)):
158+
# If narrowing only removes items, reuse unchanged instances without
159+
# checking overlap or recursively narrowing them.
160+
result_items: list[Type] = []
161+
for item in declared.relevant_items():
162+
if _can_reuse_type(item):
163+
result_items.append(item)
164+
elif _is_overlapping_type(item):
165+
result_items.append(narrow_declared_type(item, narrowed))
166+
else:
167+
result_items = [
168+
narrow_declared_type(item, narrowed)
169+
for item in declared.relevant_items()
170+
if _is_overlapping_type(item)
171+
]
172+
return make_simplified_union(result_items)
144173
if is_enum_overlapping_union(declared, narrowed):
145174
return original_narrowed
146175
elif not is_overlapping_types(declared, narrowed, prohibit_none_typevar_overlap=True):

‎mypy/test/testtypes.py‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1101,6 +1101,64 @@ def test_trivial_cases(self) -> None:
11011101
for simple in self.fx.a, self.fx.o, self.fx.b:
11021102
self.assert_meet(simple, simple, simple)
11031103

1104+
def test_narrow_large_union_of_instances(self) -> None:
1105+
fx = self.fx
1106+
items = [Instance(fx.make_type_info(f"T{i}", mro=[fx.oi]), []) for i in range(300)]
1107+
declared = UnionType(items)
1108+
# The instances may be distinct objects after expanding a type alias.
1109+
narrowed = UnionType([Instance(item.type, []) for item in items[1:]])
1110+
with state.strict_optional_set(True):
1111+
assert_equal(narrow_declared_type(declared, narrowed), narrowed)
1112+
1113+
def test_narrow_union_preserves_truthiness(self) -> None:
1114+
fx = self.fx
1115+
for strict_optional in (False, True):
1116+
with state.strict_optional_set(strict_optional):
1117+
truthy_a = true_only(fx.a)
1118+
declared = UnionType([fx.d, fx.o, truthy_a])
1119+
narrowed = UnionType([fx.d, truthy_a])
1120+
result = get_proper_type(narrow_declared_type(declared, narrowed))
1121+
assert isinstance(result, UnionType)
1122+
assert_equal(result, UnionType([fx.d, fx.a]))
1123+
result_a = next(item for item in result.items if item == fx.a)
1124+
assert result_a.can_be_true
1125+
assert result_a.can_be_false == (not strict_optional)
1126+
1127+
def test_narrow_union_with_shared_instance_and_subclass(self) -> None:
1128+
fx = self.fx
1129+
with state.strict_optional_set(True):
1130+
assert_equal(
1131+
narrow_declared_type(UnionType([fx.a, fx.b, fx.d]), UnionType([fx.b, fx.d])),
1132+
UnionType([fx.b, fx.d]),
1133+
)
1134+
assert_equal(
1135+
narrow_declared_type(UnionType([fx.a, fx.d]), UnionType([fx.b, fx.d])),
1136+
UnionType([fx.b, fx.d]),
1137+
)
1138+
1139+
def test_narrow_union_with_literal_instances(self) -> None:
1140+
fx = self.fx
1141+
declared = UnionType([fx.lit1_inst, fx.a, fx.lit2, fx.lit1])
1142+
narrowed = UnionType([fx.lit1_inst, fx.lit2])
1143+
for strict_optional in (False, True):
1144+
with state.strict_optional_set(strict_optional):
1145+
assert_equal(
1146+
narrow_declared_type(declared, narrowed), UnionType([fx.a, fx.lit1, fx.lit2])
1147+
)
1148+
1149+
def test_narrow_union_preserves_new_generic_members(self) -> None:
1150+
fx = self.fx
1151+
info = fx.make_type_info("T", mro=[fx.oi], typevars=["S"], variances=[INVARIANT])
1152+
generic_any = Instance(info, [fx.anyt])
1153+
generic_a = Instance(info, [fx.a])
1154+
declared = UnionType([generic_any, fx.d])
1155+
with state.strict_optional_set(True):
1156+
for items in ([generic_any, generic_a, fx.d], [generic_a, generic_any, fx.d]):
1157+
narrowed = UnionType(items)
1158+
result = narrow_declared_type(declared, narrowed)
1159+
assert_equal(result, narrowed)
1160+
assert_equal(str(result), str(narrowed))
1161+
11041162
def test_class_subtyping(self) -> None:
11051163
self.assert_meet(self.fx.a, self.fx.o, self.fx.a)
11061164
self.assert_meet(self.fx.a, self.fx.b, self.fx.b)

0 commit comments

Comments
 (0)