From a891598832e7894c6d580c2ed225598804422723 Mon Sep 17 00:00:00 2001 From: Svoboda <281911835+svobsl@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:25:39 +0100 Subject: [PATCH] Fix bounded generic protocol inference Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- mypy/constraints.py | 6 ++++++ test-data/unit/check-protocols.test | 24 ++++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/mypy/constraints.py b/mypy/constraints.py index aa095316c234e..51c3f2048f734 100644 --- a/mypy/constraints.py +++ b/mypy/constraints.py @@ -820,6 +820,12 @@ def visit_instance(self, template: Instance) -> list[Constraint]: # Infer constraints for Type[T] via metaclass of T when it makes sense. if isinstance(a_item, TypeVarType): a_item = get_proper_type(a_item.upper_bound) + if isinstance(a_item, Instance): + res.extend( + self.infer_constraints_from_protocol_members( + a_item, template, a_item, template, class_obj=True + ) + ) if isinstance(a_item, Instance) and a_item.type.metaclass_type: res.extend( self.infer_constraints_from_protocol_members( diff --git a/test-data/unit/check-protocols.test b/test-data/unit/check-protocols.test index 4c0fdd55b1224..3ea0022e51b53 100644 --- a/test-data/unit/check-protocols.test +++ b/test-data/unit/check-protocols.test @@ -4115,6 +4115,30 @@ def outer(cls: Type[TF]) -> TF: reveal_type(test(cls)) # N: Revealed type is "TF`-1" return cls() +[case testGenericBoundedTypeProtocolInference] +from typing import ClassVar, Protocol, TypeVar + +class Layout: ... +L_co = TypeVar("L_co", bound=Layout, covariant=True) + +class HasLayout(Protocol[L_co]): + @property + def layout(self) -> L_co: ... + +class Table: + layout: ClassVar[Layout] + +T_co = TypeVar("T_co", bound=Table, covariant=True) + +def get_layout(cls: HasLayout[L_co]) -> L_co: ... + +def concrete(cls: type[Table]) -> None: + reveal_type(get_layout(cls)) # N: Revealed type is "__main__.Layout" + +def generic(cls: type[T_co]) -> None: + reveal_type(get_layout(cls)) # N: Revealed type is "__main__.Layout" +[builtins fixtures/property.pyi] + [case testProtocolImportNotMember] import m import lib