diff --git a/mypy/constraints.py b/mypy/constraints.py index aa095316c234..ac5b23dcf9a1 100644 --- a/mypy/constraints.py +++ b/mypy/constraints.py @@ -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 diff --git a/test-data/unit/check-protocols.test b/test-data/unit/check-protocols.test index 4c0fdd55b122..db6f204361dd 100644 --- a/test-data/unit/check-protocols.test +++ b/test-data/unit/check-protocols.test @@ -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