Skip to content

Commit 222029b

Browse files
Minor proper subtype check optimization (#12536)
Mypyc is bad at compiling nested functions. In one use case we were spending 7% of the mypy runtime just creating closure objects for `check_argument`. Here I manually inline the nested function to avoid this overhead. Work on #12526. Co-authored-by: Jelle Zijlstra <[email protected]>
1 parent ab6185e commit 222029b

File tree

1 file changed

+10
-9
lines changed

1 file changed

+10
-9
lines changed

mypy/subtypes.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1370,13 +1370,6 @@ def visit_instance(self, left: Instance) -> bool:
13701370
return True
13711371

13721372
if left.type.has_base(right.type.fullname):
1373-
def check_argument(leftarg: Type, rightarg: Type, variance: int) -> bool:
1374-
if variance == COVARIANT:
1375-
return self._is_proper_subtype(leftarg, rightarg)
1376-
elif variance == CONTRAVARIANT:
1377-
return self._is_proper_subtype(rightarg, leftarg)
1378-
else:
1379-
return mypy.sametypes.is_same_type(leftarg, rightarg)
13801373
# Map left type to corresponding right instances.
13811374
left = map_instance_to_supertype(left, right.type)
13821375
if self.erase_instances:
@@ -1387,9 +1380,17 @@ def check_argument(leftarg: Type, rightarg: Type, variance: int) -> bool:
13871380
nominal = True
13881381
for ta, ra, tvar in zip(left.args, right.args, right.type.defn.type_vars):
13891382
if isinstance(tvar, TypeVarType):
1390-
nominal = nominal and check_argument(ta, ra, tvar.variance)
1383+
variance = tvar.variance
1384+
if variance == COVARIANT:
1385+
nominal = self._is_proper_subtype(ta, ra)
1386+
elif variance == CONTRAVARIANT:
1387+
nominal = self._is_proper_subtype(ra, ta)
1388+
else:
1389+
nominal = mypy.sametypes.is_same_type(ta, ra)
13911390
else:
1392-
nominal = nominal and mypy.sametypes.is_same_type(ta, ra)
1391+
nominal = mypy.sametypes.is_same_type(ta, ra)
1392+
if not nominal:
1393+
break
13931394

13941395
if nominal:
13951396
TypeState.record_subtype_cache_entry(self._subtype_kind, left, right)

0 commit comments

Comments
 (0)