Skip to content

Commit ccbf32b

Browse files
authored
Speed up bind_self() in edge cases involving protocols (#22319)
Fixes #20828 This has no effect on self-check, but improves edge cases involving self-types and protocols where currently performance is very bad. For example, `altair` should be ~2x faster. Two things here: * Use `bind_self_fast()` in situations where `type_checker` is not set (e.g. late stages of semantic analysis). * Add lightweight cache for cases where full `bind_self()` is required.
1 parent 8849b3b commit ccbf32b

7 files changed

Lines changed: 149 additions & 34 deletions

File tree

‎mypy/checkmember.py‎

Lines changed: 2 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from __future__ import annotations
44

55
from collections.abc import Callable, Sequence
6-
from typing import TypeVar, cast
6+
from typing import cast
77

88
from mypy import message_registry, state
99
from mypy.checker_shared import TypeCheckerSharedApi
@@ -21,7 +21,6 @@
2121
from mypy.nodes import (
2222
ARG_POS,
2323
ARG_STAR,
24-
ARG_STAR2,
2524
EXCLUDED_ENUM_ATTRIBUTES,
2625
SYMBOL_FUNCBASE_TYPES,
2726
Context,
@@ -45,6 +44,7 @@
4544
from mypy.subtypes import is_subtype
4645
from mypy.typeops import (
4746
bind_self,
47+
bind_self_fast,
4848
erase_to_bound,
4949
freeze_all_type_vars,
5050
get_all_type_vars,
@@ -1503,34 +1503,6 @@ def analyze_decorator_or_funcbase_access(
15031503
return bind_self(typ, original_type=mx.self_type, is_classmethod=defn.is_class)
15041504

15051505

1506-
F = TypeVar("F", bound=FunctionLike)
1507-
1508-
1509-
def bind_self_fast(method: F, original_type: Type | None = None) -> F:
1510-
"""Return a copy of `method`, with the type of its first parameter (usually
1511-
self or cls) bound to original_type.
1512-
1513-
This is a faster version of mypy.typeops.bind_self() that can be used for methods
1514-
with trivial self/cls annotations.
1515-
"""
1516-
if isinstance(method, Overloaded):
1517-
items = [bind_self_fast(c, original_type) for c in method.items]
1518-
return cast(F, Overloaded(items))
1519-
assert isinstance(method, CallableType)
1520-
if not method.arg_types:
1521-
# Invalid method, return something.
1522-
return method
1523-
if method.arg_kinds[0] in (ARG_STAR, ARG_STAR2):
1524-
# See typeops.py for details.
1525-
return method
1526-
return method.copy_modified(
1527-
arg_types=method.arg_types[1:],
1528-
arg_kinds=method.arg_kinds[1:],
1529-
arg_names=method.arg_names[1:],
1530-
is_bound=True,
1531-
)
1532-
1533-
15341506
def has_operator(typ: Type, op_method: str) -> bool:
15351507
"""Does type have operator with the given name?
15361508

‎mypy/server/update.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -887,6 +887,7 @@ def propagate_changes_using_dependencies(
887887
# unchanged, but was marked stale because its sub- (or super-) type changed.
888888
for info in stale_protos:
889889
type_state.reset_subtype_caches_for(info)
890+
type_state.bind_self_cache.clear()
890891
# Then fully reprocess all targets.
891892
# TODO: Preserve order (set is not optimal)
892893
for id, nodes in sorted(todo.items(), key=lambda x: x[0]):

‎mypy/subtypes.py‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
Context,
3131
Decorator,
3232
FuncBase,
33+
FuncDef,
3334
OverloadedFuncDef,
3435
TypeInfo,
3536
Var,
@@ -1489,6 +1490,7 @@ def find_member(
14891490
# to avoid type variable id collisions, but for protocols this means we can't
14901491
# use the assumption stack, that will grow indefinitely.
14911492
# TODO: find a cleaner solution that doesn't involve massive perf impact.
1493+
# Note: bind_self() cache relies on this, update it if this is changed.
14921494
preserve_type_var_ids=True,
14931495
)
14941496
with type_checker.msg.filter_errors(filter_deprecated=True):
@@ -1645,8 +1647,6 @@ def find_node_type(
16451647
"""Find type of a variable or method 'node' (maybe also a decorated method).
16461648
Apply type arguments from 'itype', and bind 'self' to 'subtype'.
16471649
"""
1648-
from mypy.typeops import bind_self
1649-
16501650
if isinstance(node, FuncBase):
16511651
typ: Type | None = mypy.typeops.function_type(
16521652
node, fallback=Instance(itype.type.mro[-1], [])
@@ -1676,8 +1676,10 @@ def find_node_type(
16761676
):
16771677
# Don't bind instance methods on class objects.
16781678
signature = p_typ
1679+
elif isinstance(node, (FuncDef, OverloadedFuncDef)) and node.is_trivial_self:
1680+
signature = mypy.typeops.bind_self_fast(p_typ, subtype)
16791681
else:
1680-
signature = bind_self(
1682+
signature = mypy.typeops.bind_self(
16811683
p_typ, subtype, is_classmethod=isinstance(node, Var) and node.is_classmethod
16821684
)
16831685
if node.is_property and not class_obj:

‎mypy/typeops.py‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@
7272
instance_cache,
7373
remove_dups,
7474
)
75+
from mypy.typestate import BIND_SELF_CACHE_MAX_SIZE, type_state
7576
from mypy.typetraverser import TypeTraverserVisitor
7677
from mypy.typevars import fill_typevars
7778

@@ -551,6 +552,14 @@ def bind_self_inner(
551552
self_ids = {tv.id for tv in get_all_type_vars(self_param_type)}
552553
self_vars = [tv for tv in func.variables if tv.id in self_ids]
553554

555+
cache_key = None
556+
if not any(tv.id.is_meta_var() for tv in self_vars) and state.strict_optional:
557+
# Only use cache for something that in not freshened (e.g. protocol access),
558+
# otherwise it would be pointless as each fresh meta variable is unique.
559+
cache_key = (func, original_type, is_classmethod, ignore_instances)
560+
if cache_key is not None and cache_key in type_state.bind_self_cache:
561+
return type_state.bind_self_cache[cache_key]
562+
554563
# Solve for these type arguments using the actual class or instance type.
555564
typeargs = infer_type_arguments(
556565
self_vars, self_param_type, original_type, is_supertype=True, erase_types=False
@@ -574,11 +583,40 @@ def bind_self_inner(
574583
to_apply = [t if t is not None else UninhabitedType() for t in typeargs]
575584
func = expand_type(func, {tv.id: arg for tv, arg in zip(self_vars, to_apply)})
576585
variables = [v for v in func.variables if v not in self_vars]
586+
if cache_key is not None:
587+
if len(type_state.bind_self_cache) > BIND_SELF_CACHE_MAX_SIZE:
588+
type_state.bind_self_cache.clear()
589+
type_state.bind_self_cache[cache_key] = func, variables
577590
else:
578591
variables = func.variables
579592
return func, variables
580593

581594

595+
def bind_self_fast(method: F, original_type: Type | None = None) -> F:
596+
"""Return a copy of `method`, with the type of its first parameter (usually
597+
self or cls) bound to original_type.
598+
599+
This is a faster version of mypy.typeops.bind_self() that can be used for methods
600+
with trivial self/cls annotations.
601+
"""
602+
if isinstance(method, Overloaded):
603+
items = [bind_self_fast(c, original_type) for c in method.items]
604+
return cast(F, Overloaded(items))
605+
assert isinstance(method, CallableType)
606+
if not method.arg_types:
607+
# Invalid method, return something.
608+
return method
609+
if method.arg_kinds[0] in (ARG_STAR, ARG_STAR2):
610+
# See bind_self() for details.
611+
return method
612+
return method.copy_modified(
613+
arg_types=method.arg_types[1:],
614+
arg_kinds=method.arg_kinds[1:],
615+
arg_names=method.arg_names[1:],
616+
is_bound=True,
617+
)
618+
619+
582620
def erase_to_bound(t: Type) -> Type:
583621
# TODO: use value restrictions to produce a union?
584622
t = get_proper_type(t)

‎mypy/typestate.py‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,29 @@
55

66
from __future__ import annotations
77

8+
from collections.abc import Sequence
89
from typing import Final, TypeAlias as _TypeAlias
910

1011
from mypy.nodes import VARIANCE_NOT_READY, TypeInfo
1112
from mypy.server.trigger import make_trigger
12-
from mypy.types import Instance, Type, TypeVarId, TypeVarType, get_proper_type
13+
from mypy.types import (
14+
CallableType,
15+
Instance,
16+
Type,
17+
TypeVarId,
18+
TypeVarLikeType,
19+
TypeVarType,
20+
get_proper_type,
21+
)
1322

1423
MAX_NEGATIVE_CACHE_TYPES: Final = 1000
1524
MAX_NEGATIVE_CACHE_ENTRIES: Final = 10000
1625

26+
BindSelfCacheKey = tuple[CallableType, Type, bool, bool]
27+
BindSelfCacheValue = tuple[CallableType, Sequence[TypeVarLikeType]]
28+
29+
BIND_SELF_CACHE_MAX_SIZE: Final = 10000
30+
1731
# Represents that the 'left' instance is a subtype of the 'right' instance
1832
SubtypeRelationship: _TypeAlias = tuple[Instance, Instance]
1933

@@ -47,6 +61,10 @@ class TypeState:
4761
# Same as above but for negative subtyping results.
4862
_negative_subtype_caches: Final[SubtypeCache]
4963

64+
# A dedicated lightweight cache for bind_self(), which may be slow because of type
65+
# inference in some scenarios involving protocols with non-trivial self-types.
66+
bind_self_cache: Final[dict[BindSelfCacheKey, BindSelfCacheValue]]
67+
5068
# This contains protocol dependencies generated after running a full build,
5169
# or after an update. These dependencies are special because:
5270
# * They are a global property of the program; i.e. some dependencies for imported
@@ -119,6 +137,7 @@ def __init__(self) -> None:
119137
self.infer_unions = False
120138
self.infer_polymorphic = False
121139
self.keep_unions = False
140+
self.bind_self_cache = {}
122141

123142
def is_assumed_subtype(self, left: Type, right: Type) -> bool:
124143
for l, r in reversed(self._assuming):
@@ -331,4 +350,5 @@ def reset_global_state() -> None:
331350
"""
332351
type_state.reset_all_subtype_caches()
333352
type_state.reset_protocol_deps()
353+
type_state.bind_self_cache.clear()
334354
TypeVarId.next_raw_id = 1

‎test-data/unit/check-protocols.test‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4819,3 +4819,49 @@ class Bad(Generic[T]):
48194819
bad: Bad[str] = Bad()
48204820
fail: SupportsFoo = bad # E: Incompatible types in assignment (expression has type "Bad[str]", variable has type "SupportsFoo")
48214821
[builtins fixtures/tuple.pyi]
4822+
4823+
[case testProtocolGenericSelfTypeInTypeArgumentBound]
4824+
from typing import Generic, Protocol, TypeVar
4825+
from b import Base
4826+
4827+
class P(Protocol):
4828+
def meth(self) -> int: ...
4829+
4830+
class C(Base[int]): pass
4831+
class D(Base[str]): pass
4832+
4833+
PT = TypeVar("PT", bound=P)
4834+
class Box(Generic[PT]): pass
4835+
4836+
x: Box[C]
4837+
y: Box[D] # E: Type argument "D" of "Box" must be a subtype of "P"
4838+
[file b.pyi]
4839+
from typing import Generic, TypeVar
4840+
T = TypeVar("T")
4841+
S = TypeVar("S")
4842+
class Base(Generic[T]):
4843+
def meth(self: Base[S]) -> S: ...
4844+
4845+
[case testProtocolImplicitClassmethodSelfTypeInTypeArgumentBound]
4846+
from typing import Callable, Generic, Protocol, TypeVar
4847+
from b import C
4848+
4849+
class P(Protocol):
4850+
def __init_subclass__(cls, item: Callable[[str], None]) -> None: ...
4851+
4852+
PT = TypeVar("PT", bound=P)
4853+
class Box(Generic[PT]): pass
4854+
4855+
x: Box[C]
4856+
def f(x: P) -> None: pass
4857+
f(C()) # E: Argument 1 to "f" has incompatible type "C"; expected "P" \
4858+
# N: Following member(s) of "C" have conflicts: \
4859+
# N: Expected: \
4860+
# N: def __init_subclass__(cls, item: Callable[[str], None]) -> None \
4861+
# N: Got: \
4862+
# N: def __init_subclass__(cls, item: Callable[[C], None]) -> None
4863+
[file b.pyi]
4864+
from typing import Callable, TypeVar
4865+
S = TypeVar("S")
4866+
class C:
4867+
def __init_subclass__(cls: type[S], item: Callable[[S], None]) -> None: ...

‎test-data/unit/fine-grained.test‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11970,3 +11970,39 @@ class C: pass
1197011970
[out]
1197111971
==
1197211972
main:3: error: Name "C" is not defined
11973+
11974+
[case testProtocolGenericSelfTypeBaseChanged]
11975+
import a
11976+
[file a.py]
11977+
from b import P
11978+
from d import C
11979+
def f(x: P) -> None: pass
11980+
f(C())
11981+
[file b.py]
11982+
from typing import Protocol
11983+
class P(Protocol):
11984+
def meth(self) -> int: ...
11985+
[file c.py]
11986+
from typing import Generic, TypeVar
11987+
T = TypeVar("T")
11988+
S = TypeVar("S")
11989+
class Base(Generic[T]):
11990+
def meth(self: "Base[S]") -> S: ...
11991+
[file d.py]
11992+
from c import Base
11993+
class C(Base[int]): pass
11994+
[file d.py.2]
11995+
from c import Base
11996+
class C(Base[str]): pass
11997+
[file d.py.3]
11998+
from c import Base
11999+
class C(Base[int]): pass
12000+
[out]
12001+
==
12002+
a.py:4: error: Argument 1 to "f" has incompatible type "C"; expected "P"
12003+
a.py:4: note: Following member(s) of "C" have conflicts:
12004+
a.py:4: note: Expected:
12005+
a.py:4: note: def meth(self) -> int
12006+
a.py:4: note: Got:
12007+
a.py:4: note: def meth(self) -> str
12008+
==

0 commit comments

Comments
 (0)