Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions mypy/constraints.py
Original file line number Diff line number Diff line change
Expand Up @@ -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, actual, template, class_obj=True
)
)
if isinstance(a_item, Instance) and a_item.type.metaclass_type:
res.extend(
self.infer_constraints_from_protocol_members(
Expand Down
25 changes: 25 additions & 0 deletions test-data/unit/check-protocols.test
Original file line number Diff line number Diff line change
Expand Up @@ -4865,3 +4865,28 @@ from typing import Callable, TypeVar
S = TypeVar("S")
class C:
def __init_subclass__(cls: type[S], item: Callable[[S], None]) -> None: ...

[case testProtocolInferenceFromBoundTypeVarClassObject]
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:
return cls.layout

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]
Loading