← Back to index

protocols_self.py

True Positive
False Positive
False Negative
Optional (detected)
Warning or Info
TP: 0
FP: 0
FN: 0
Optional: 0 / 0
1"""
2Tests the handling of annotated "self" parameters in a protocol.
3"""
4
5# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#self-types-in-protocols
6
7from typing import Generic, Protocol, Self, TypeVar
8
9
10C = TypeVar("C", bound="Copyable")
13class Copyable(Protocol):
14 def copy(self: C) -> C:
15 return self
18class One:
19 def copy(self) -> "One":
20 return One()
23T = TypeVar("T", bound="Other")
26class Other:
27 def copy(self: T) -> T:
28 return self
31c: Copyable
32c = One() # OK
33c = Other() # OK
36T1_co = TypeVar("T1_co", covariant=True)
37T2_co = TypeVar("T2_co", covariant=True)
40class P1Parent(Protocol[T2_co]):
41 def f0(self, /) -> Self:
42 ...
45class P1Child(P1Parent[T2_co], Protocol[T2_co]):
46 ...
49class C1(Generic[T1_co]):
50 def f0(self, /) -> Self:
51 return self
54a1: P1Parent[str] = C1[str]()
55b1: P1Child[str] = C1[str]()
58class P2Parent(Protocol[T1_co]):
59 def f0(self, right: Self, /) -> "P2Parent[T1_co]":
60 return right
63class P2Child(P2Parent[T1_co], Protocol[T1_co]):
64 ...
67class C2(Generic[T2_co]):
68 def f0(self, other: Self) -> "C2[T2_co]":
69 return other
72a2: P2Parent[str] = C2[str]() # OK
73b2: P2Child[str] = C2[str]() # OK