Skip to content
Draft
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
17 changes: 14 additions & 3 deletions mypy/constraints.py
Original file line number Diff line number Diff line change
Expand Up @@ -1005,12 +1005,23 @@ def visit_instance(self, template: Instance) -> list[Constraint]:
and mypy.subtypes.is_protocol_implementation(erased, instance, skip=["__call__"])
):
instance.type.inferring.append(instance)
member_constraints = self.infer_constraints_from_protocol_members(
instance, template, template, instance
)
instance.type.inferring.pop()
# Binding the protocol's Self to the template can produce
# constraints such as T <: T. These give no contextual information
# about the inference variable T.
res.extend(
self.infer_constraints_from_protocol_members(
instance, template, template, instance
c
for c in member_constraints
if not (
isinstance(c.target, TypeVarType)
and c.type_var.is_meta_var()
and c.target == c.origin_type_var
and not c.extra_tvars
)
)
instance.type.inferring.pop()
return res
if res:
return res
Expand Down
37 changes: 37 additions & 0 deletions test-data/unit/check-protocols.test
Original file line number Diff line number Diff line change
Expand Up @@ -4760,6 +4760,43 @@ class A(Protocol):

[builtins fixtures/tuple.pyi]

[case testInlineListWithGenericSelfProtocolContext]
from typing import Protocol, Self, TypeVar

T_co = TypeVar("T_co", covariant=True)
T = TypeVar("T")

class Concatenable(Protocol[T_co]):
def __add__(self, other: Self) -> Self: ...

def duplicate(seq: Concatenable[T]) -> Concatenable[T]:
return seq + seq

items = [1, 2, 3]
duplicate(items)
duplicate([1, 2, 3])
[builtins fixtures/list.pyi]

[case testInlineListWithConstrainedSelfProtocolContext]
from typing import Literal, Protocol, Self, TypeVar

T_co = TypeVar("T_co", covariant=True)
T = TypeVar("T")

class Concatenable(Protocol[T_co]):
def __add__(self, other: Self) -> Self: ...
def __getitem__(self, index: int, /) -> T_co: ...

def first(x: Concatenable[T]) -> T:
return x[0]

def expect_one(x: Concatenable[Literal[1]]) -> None: ...

reveal_type(first([1, 2])) # N: Revealed type is "builtins.int"
expect_one([1])
expect_one([2]) # E: List item 0 has incompatible type "Literal[2]"; expected "Literal[1]"
[builtins fixtures/list.pyi]

[case testTupleTypeSelfTypeProto]
from typing import Protocol, TypeVar

Expand Down
Loading