From 27ef01f7bcdc1ae4afaca13668c10a1fdcda77ff Mon Sep 17 00:00:00 2001 From: Ivan Levkivskyi Date: Mon, 26 Oct 2026 23:40:40 +0000 Subject: [PATCH 1/8] Move bind_self_fast to typeops --- mypy/checkmember.py | 32 ++------------------------------ mypy/typeops.py | 25 +++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 30 deletions(-) diff --git a/mypy/checkmember.py b/mypy/checkmember.py index 08bcdab8d0a20..e01d1e6a85790 100644 --- a/mypy/checkmember.py +++ b/mypy/checkmember.py @@ -3,7 +3,7 @@ from __future__ import annotations from collections.abc import Callable, Sequence -from typing import TypeVar, cast +from typing import cast from mypy import message_registry, state from mypy.checker_shared import TypeCheckerSharedApi @@ -21,7 +21,6 @@ from mypy.nodes import ( ARG_POS, ARG_STAR, - ARG_STAR2, EXCLUDED_ENUM_ATTRIBUTES, SYMBOL_FUNCBASE_TYPES, Context, @@ -45,6 +44,7 @@ from mypy.subtypes import is_subtype from mypy.typeops import ( bind_self, + bind_self_fast, erase_to_bound, freeze_all_type_vars, get_all_type_vars, @@ -1503,34 +1503,6 @@ def analyze_decorator_or_funcbase_access( return bind_self(typ, original_type=mx.self_type, is_classmethod=defn.is_class) -F = TypeVar("F", bound=FunctionLike) - - -def bind_self_fast(method: F, original_type: Type | None = None) -> F: - """Return a copy of `method`, with the type of its first parameter (usually - self or cls) bound to original_type. - - This is a faster version of mypy.typeops.bind_self() that can be used for methods - with trivial self/cls annotations. - """ - if isinstance(method, Overloaded): - items = [bind_self_fast(c, original_type) for c in method.items] - return cast(F, Overloaded(items)) - assert isinstance(method, CallableType) - if not method.arg_types: - # Invalid method, return something. - return method - if method.arg_kinds[0] in (ARG_STAR, ARG_STAR2): - # See typeops.py for details. - return method - return method.copy_modified( - arg_types=method.arg_types[1:], - arg_kinds=method.arg_kinds[1:], - arg_names=method.arg_names[1:], - is_bound=True, - ) - - def has_operator(typ: Type, op_method: str) -> bool: """Does type have operator with the given name? diff --git a/mypy/typeops.py b/mypy/typeops.py index eb9d0d1474b8b..319d0c6c4580e 100644 --- a/mypy/typeops.py +++ b/mypy/typeops.py @@ -579,6 +579,31 @@ def bind_self_inner( return func, variables +def bind_self_fast(method: F, original_type: Type | None = None) -> F: + """Return a copy of `method`, with the type of its first parameter (usually + self or cls) bound to original_type. + + This is a faster version of mypy.typeops.bind_self() that can be used for methods + with trivial self/cls annotations. + """ + if isinstance(method, Overloaded): + items = [bind_self_fast(c, original_type) for c in method.items] + return cast(F, Overloaded(items)) + assert isinstance(method, CallableType) + if not method.arg_types: + # Invalid method, return something. + return method + if method.arg_kinds[0] in (ARG_STAR, ARG_STAR2): + # See typeops.py for details. + return method + return method.copy_modified( + arg_types=method.arg_types[1:], + arg_kinds=method.arg_kinds[1:], + arg_names=method.arg_names[1:], + is_bound=True, + ) + + def erase_to_bound(t: Type) -> Type: # TODO: use value restrictions to produce a union? t = get_proper_type(t) From d6bbae17af2c45ef89391d460e1ebb9e5eb462aa Mon Sep 17 00:00:00 2001 From: Ivan Levkivskyi Date: Mon, 26 Oct 2026 23:48:03 +0000 Subject: [PATCH 2/8] Use bind_self_fast in find_node_type --- mypy/subtypes.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/mypy/subtypes.py b/mypy/subtypes.py index 17b818c49c677..ceffd8a93116c 100644 --- a/mypy/subtypes.py +++ b/mypy/subtypes.py @@ -30,6 +30,7 @@ Context, Decorator, FuncBase, + FuncDef, OverloadedFuncDef, TypeInfo, Var, @@ -1645,7 +1646,7 @@ def find_node_type( """Find type of a variable or method 'node' (maybe also a decorated method). Apply type arguments from 'itype', and bind 'self' to 'subtype'. """ - from mypy.typeops import bind_self + from mypy.typeops import bind_self, bind_self_fast if isinstance(node, FuncBase): typ: Type | None = mypy.typeops.function_type( @@ -1676,6 +1677,8 @@ def find_node_type( ): # Don't bind instance methods on class objects. signature = p_typ + elif isinstance(node, (FuncDef, OverloadedFuncDef)): + signature = bind_self_fast(p_typ, subtype) else: signature = bind_self( p_typ, subtype, is_classmethod=isinstance(node, Var) and node.is_classmethod From 5ebf3397320ab4d1b51fc5c24b143a072e4bf009 Mon Sep 17 00:00:00 2001 From: Ivan Levkivskyi Date: Wed, 28 Oct 2026 21:17:43 +0000 Subject: [PATCH 3/8] Fix --- mypy/subtypes.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/mypy/subtypes.py b/mypy/subtypes.py index ceffd8a93116c..98c645855700f 100644 --- a/mypy/subtypes.py +++ b/mypy/subtypes.py @@ -1646,8 +1646,6 @@ def find_node_type( """Find type of a variable or method 'node' (maybe also a decorated method). Apply type arguments from 'itype', and bind 'self' to 'subtype'. """ - from mypy.typeops import bind_self, bind_self_fast - if isinstance(node, FuncBase): typ: Type | None = mypy.typeops.function_type( node, fallback=Instance(itype.type.mro[-1], []) @@ -1677,10 +1675,10 @@ def find_node_type( ): # Don't bind instance methods on class objects. signature = p_typ - elif isinstance(node, (FuncDef, OverloadedFuncDef)): - signature = bind_self_fast(p_typ, subtype) + elif isinstance(node, (FuncDef, OverloadedFuncDef)) and node.is_trivial_self: + signature = mypy.typeops.bind_self_fast(p_typ, subtype) else: - signature = bind_self( + signature = mypy.typeops.bind_self( p_typ, subtype, is_classmethod=isinstance(node, Var) and node.is_classmethod ) if node.is_property and not class_obj: From 2651d5a9a3377d43d3bd08200098ef21d63a4a6f Mon Sep 17 00:00:00 2001 From: Ivan Levkivskyi Date: Thu, 29 Oct 2026 16:22:59 +0000 Subject: [PATCH 4/8] Add cache to bind_self() --- mypy/subtypes.py | 1 + mypy/typeops.py | 22 ++++++++++++++++++++-- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/mypy/subtypes.py b/mypy/subtypes.py index 98c645855700f..ca21e67f3a6e5 100644 --- a/mypy/subtypes.py +++ b/mypy/subtypes.py @@ -1490,6 +1490,7 @@ def find_member( # to avoid type variable id collisions, but for protocols this means we can't # use the assumption stack, that will grow indefinitely. # TODO: find a cleaner solution that doesn't involve massive perf impact. + # Note: bind_self() cache relies on this, update it if this is changed. preserve_type_var_ids=True, ) with type_checker.msg.filter_errors(filter_deprecated=True): diff --git a/mypy/typeops.py b/mypy/typeops.py index 319d0c6c4580e..210a88f1e894c 100644 --- a/mypy/typeops.py +++ b/mypy/typeops.py @@ -9,7 +9,7 @@ import itertools from collections.abc import Callable, Iterable, Sequence -from typing import Any, TypeVar, cast +from typing import Any, Final, TypeVar, cast import mypy.subtypes from mypy.checker_state import checker_state @@ -75,6 +75,12 @@ from mypy.typetraverser import TypeTraverserVisitor from mypy.typevars import fill_typevars +BindSelfCacheKey = tuple[CallableType, Type, bool, bool] +BindSelfCacheValue = tuple[CallableType, Sequence[TypeVarLikeType]] + +BIND_SELF_CACHE: Final[dict[BindSelfCacheKey, BindSelfCacheValue]] = {} +BIND_SELF_CACHE_MAX_SIZE: Final = 10000 + def is_recursive_pair(s: Type, t: Type) -> bool: """Is this a pair of recursive types? @@ -551,6 +557,14 @@ def bind_self_inner( self_ids = {tv.id for tv in get_all_type_vars(self_param_type)} self_vars = [tv for tv in func.variables if tv.id in self_ids] + cache_key = None + if any(tv.id.is_meta_var() for tv in self_vars): + # Only use cache for something that in not freshened (e.g. protocol access), + # otherwise it would be pointless as each fresh meta variable is unique. + cache_key = (func, original_type, is_classmethod, ignore_instances) + if cache_key is not None and cache_key in BIND_SELF_CACHE: + return BIND_SELF_CACHE[cache_key] + # Solve for these type arguments using the actual class or instance type. typeargs = infer_type_arguments( self_vars, self_param_type, original_type, is_supertype=True, erase_types=False @@ -574,6 +588,10 @@ def bind_self_inner( to_apply = [t if t is not None else UninhabitedType() for t in typeargs] func = expand_type(func, {tv.id: arg for tv, arg in zip(self_vars, to_apply)}) variables = [v for v in func.variables if v not in self_vars] + if cache_key is not None: + if len(BIND_SELF_CACHE) > BIND_SELF_CACHE_MAX_SIZE: + BIND_SELF_CACHE.clear() + BIND_SELF_CACHE[cache_key] = func, variables else: variables = func.variables return func, variables @@ -594,7 +612,7 @@ def bind_self_fast(method: F, original_type: Type | None = None) -> F: # Invalid method, return something. return method if method.arg_kinds[0] in (ARG_STAR, ARG_STAR2): - # See typeops.py for details. + # See bind_self() for details. return method return method.copy_modified( arg_types=method.arg_types[1:], From 6bbd3a3bf1687174fc82b2e323adfaff263fe060 Mon Sep 17 00:00:00 2001 From: Ivan Levkivskyi Date: Thu, 29 Oct 2026 16:52:50 +0000 Subject: [PATCH 5/8] Fix --- mypy/typeops.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mypy/typeops.py b/mypy/typeops.py index 210a88f1e894c..f377976b99c4c 100644 --- a/mypy/typeops.py +++ b/mypy/typeops.py @@ -558,7 +558,7 @@ def bind_self_inner( self_vars = [tv for tv in func.variables if tv.id in self_ids] cache_key = None - if any(tv.id.is_meta_var() for tv in self_vars): + if not any(tv.id.is_meta_var() for tv in self_vars) and state.strict_optional: # Only use cache for something that in not freshened (e.g. protocol access), # otherwise it would be pointless as each fresh meta variable is unique. cache_key = (func, original_type, is_classmethod, ignore_instances) From 6da52f4fe0224da15c7e659494d8c15c92f22c1b Mon Sep 17 00:00:00 2001 From: Ivan Levkivskyi Date: Thu, 29 Oct 2026 17:08:22 +0000 Subject: [PATCH 6/8] Put it together with other caches --- mypy/typeops.py | 19 +++++++------------ mypy/typestate.py | 22 +++++++++++++++++++++- 2 files changed, 28 insertions(+), 13 deletions(-) diff --git a/mypy/typeops.py b/mypy/typeops.py index f377976b99c4c..9046be7498338 100644 --- a/mypy/typeops.py +++ b/mypy/typeops.py @@ -9,7 +9,7 @@ import itertools from collections.abc import Callable, Iterable, Sequence -from typing import Any, Final, TypeVar, cast +from typing import Any, TypeVar, cast import mypy.subtypes from mypy.checker_state import checker_state @@ -72,15 +72,10 @@ instance_cache, remove_dups, ) +from mypy.typestate import BIND_SELF_CACHE_MAX_SIZE, type_state from mypy.typetraverser import TypeTraverserVisitor from mypy.typevars import fill_typevars -BindSelfCacheKey = tuple[CallableType, Type, bool, bool] -BindSelfCacheValue = tuple[CallableType, Sequence[TypeVarLikeType]] - -BIND_SELF_CACHE: Final[dict[BindSelfCacheKey, BindSelfCacheValue]] = {} -BIND_SELF_CACHE_MAX_SIZE: Final = 10000 - def is_recursive_pair(s: Type, t: Type) -> bool: """Is this a pair of recursive types? @@ -562,8 +557,8 @@ def bind_self_inner( # Only use cache for something that in not freshened (e.g. protocol access), # otherwise it would be pointless as each fresh meta variable is unique. cache_key = (func, original_type, is_classmethod, ignore_instances) - if cache_key is not None and cache_key in BIND_SELF_CACHE: - return BIND_SELF_CACHE[cache_key] + if cache_key is not None and cache_key in type_state.bind_self_cache: + return type_state.bind_self_cache[cache_key] # Solve for these type arguments using the actual class or instance type. typeargs = infer_type_arguments( @@ -589,9 +584,9 @@ def bind_self_inner( func = expand_type(func, {tv.id: arg for tv, arg in zip(self_vars, to_apply)}) variables = [v for v in func.variables if v not in self_vars] if cache_key is not None: - if len(BIND_SELF_CACHE) > BIND_SELF_CACHE_MAX_SIZE: - BIND_SELF_CACHE.clear() - BIND_SELF_CACHE[cache_key] = func, variables + if len(type_state.bind_self_cache) > BIND_SELF_CACHE_MAX_SIZE: + type_state.bind_self_cache.clear() + type_state.bind_self_cache[cache_key] = func, variables else: variables = func.variables return func, variables diff --git a/mypy/typestate.py b/mypy/typestate.py index f820288129cc0..a1514592d779e 100644 --- a/mypy/typestate.py +++ b/mypy/typestate.py @@ -5,15 +5,29 @@ from __future__ import annotations +from collections.abc import Sequence from typing import Final, TypeAlias as _TypeAlias from mypy.nodes import VARIANCE_NOT_READY, TypeInfo from mypy.server.trigger import make_trigger -from mypy.types import Instance, Type, TypeVarId, TypeVarType, get_proper_type +from mypy.types import ( + CallableType, + Instance, + Type, + TypeVarId, + TypeVarLikeType, + TypeVarType, + get_proper_type, +) MAX_NEGATIVE_CACHE_TYPES: Final = 1000 MAX_NEGATIVE_CACHE_ENTRIES: Final = 10000 +BindSelfCacheKey = tuple[CallableType, Type, bool, bool] +BindSelfCacheValue = tuple[CallableType, Sequence[TypeVarLikeType]] + +BIND_SELF_CACHE_MAX_SIZE: Final = 10000 + # Represents that the 'left' instance is a subtype of the 'right' instance SubtypeRelationship: _TypeAlias = tuple[Instance, Instance] @@ -47,6 +61,10 @@ class TypeState: # Same as above but for negative subtyping results. _negative_subtype_caches: Final[SubtypeCache] + # A dedicated lightweight cache for bind_self(), which may be slow because of type + # inference in some scenarios involving protocols with non-trivial self-types. + bind_self_cache: Final[dict[BindSelfCacheKey, BindSelfCacheValue]] + # This contains protocol dependencies generated after running a full build, # or after an update. These dependencies are special because: # * They are a global property of the program; i.e. some dependencies for imported @@ -119,6 +137,7 @@ def __init__(self) -> None: self.infer_unions = False self.infer_polymorphic = False self.keep_unions = False + self.bind_self_cache = {} def is_assumed_subtype(self, left: Type, right: Type) -> bool: for l, r in reversed(self._assuming): @@ -331,4 +350,5 @@ def reset_global_state() -> None: """ type_state.reset_all_subtype_caches() type_state.reset_protocol_deps() + type_state.bind_self_cache.clear() TypeVarId.next_raw_id = 1 From bf10f368b2ef22e755dc12067a6c87ecb88166b6 Mon Sep 17 00:00:00 2001 From: Ivan Levkivskyi Date: Fri, 30 Oct 2026 14:30:19 +0000 Subject: [PATCH 7/8] Fix daemon --- mypy/server/update.py | 1 + test-data/unit/fine-grained.test | 36 ++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/mypy/server/update.py b/mypy/server/update.py index cb7ff60e14cba..0500d23ad7162 100644 --- a/mypy/server/update.py +++ b/mypy/server/update.py @@ -887,6 +887,7 @@ def propagate_changes_using_dependencies( # unchanged, but was marked stale because its sub- (or super-) type changed. for info in stale_protos: type_state.reset_subtype_caches_for(info) + type_state.bind_self_cache.clear() # Then fully reprocess all targets. # TODO: Preserve order (set is not optimal) for id, nodes in sorted(todo.items(), key=lambda x: x[0]): diff --git a/test-data/unit/fine-grained.test b/test-data/unit/fine-grained.test index bbf23a947dc87..60dd11ad3da26 100644 --- a/test-data/unit/fine-grained.test +++ b/test-data/unit/fine-grained.test @@ -11970,3 +11970,39 @@ class C: pass [out] == main:3: error: Name "C" is not defined + +[case testProtocolGenericSelfTypeBaseChanged] +import a +[file a.py] +from b import P +from d import C +def f(x: P) -> None: pass +f(C()) +[file b.py] +from typing import Protocol +class P(Protocol): + def meth(self) -> int: ... +[file c.py] +from typing import Generic, TypeVar +T = TypeVar("T") +S = TypeVar("S") +class Base(Generic[T]): + def meth(self: "Base[S]") -> S: ... +[file d.py] +from c import Base +class C(Base[int]): pass +[file d.py.2] +from c import Base +class C(Base[str]): pass +[file d.py.3] +from c import Base +class C(Base[int]): pass +[out] +== +a.py:4: error: Argument 1 to "f" has incompatible type "C"; expected "P" +a.py:4: note: Following member(s) of "C" have conflicts: +a.py:4: note: Expected: +a.py:4: note: def meth(self) -> int +a.py:4: note: Got: +a.py:4: note: def meth(self) -> str +== From 68caff5ee8427501cd01bc3dc41275421ba363a1 Mon Sep 17 00:00:00 2001 From: Ivan Levkivskyi Date: Mon, 2 Nov 2026 16:47:38 +0000 Subject: [PATCH 8/8] Add couple regression tests --- test-data/unit/check-protocols.test | 46 +++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/test-data/unit/check-protocols.test b/test-data/unit/check-protocols.test index 75a0dfe2f5f45..4c0fdd55b1224 100644 --- a/test-data/unit/check-protocols.test +++ b/test-data/unit/check-protocols.test @@ -4819,3 +4819,49 @@ class Bad(Generic[T]): bad: Bad[str] = Bad() fail: SupportsFoo = bad # E: Incompatible types in assignment (expression has type "Bad[str]", variable has type "SupportsFoo") [builtins fixtures/tuple.pyi] + +[case testProtocolGenericSelfTypeInTypeArgumentBound] +from typing import Generic, Protocol, TypeVar +from b import Base + +class P(Protocol): + def meth(self) -> int: ... + +class C(Base[int]): pass +class D(Base[str]): pass + +PT = TypeVar("PT", bound=P) +class Box(Generic[PT]): pass + +x: Box[C] +y: Box[D] # E: Type argument "D" of "Box" must be a subtype of "P" +[file b.pyi] +from typing import Generic, TypeVar +T = TypeVar("T") +S = TypeVar("S") +class Base(Generic[T]): + def meth(self: Base[S]) -> S: ... + +[case testProtocolImplicitClassmethodSelfTypeInTypeArgumentBound] +from typing import Callable, Generic, Protocol, TypeVar +from b import C + +class P(Protocol): + def __init_subclass__(cls, item: Callable[[str], None]) -> None: ... + +PT = TypeVar("PT", bound=P) +class Box(Generic[PT]): pass + +x: Box[C] +def f(x: P) -> None: pass +f(C()) # E: Argument 1 to "f" has incompatible type "C"; expected "P" \ + # N: Following member(s) of "C" have conflicts: \ + # N: Expected: \ + # N: def __init_subclass__(cls, item: Callable[[str], None]) -> None \ + # N: Got: \ + # N: def __init_subclass__(cls, item: Callable[[C], None]) -> None +[file b.pyi] +from typing import Callable, TypeVar +S = TypeVar("S") +class C: + def __init_subclass__(cls: type[S], item: Callable[[S], None]) -> None: ...