File size: 1,243 Bytes
d8a7ddd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
"""
Tests the handling of annotated "self" parameters in a protocol.
"""

# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#self-types-in-protocols

from typing import Generic, Protocol, Self, TypeVar


C = TypeVar("C", bound="Copyable")


class Copyable(Protocol):
    def copy(self: C) -> C:
        return self


class One:
    def copy(self) -> "One":
        return One()


T = TypeVar("T", bound="Other")


class Other:
    def copy(self: T) -> T:
        return self


c: Copyable
c = One()  # OK
c = Other()  # OK


T1_co = TypeVar("T1_co", covariant=True)
T2_co = TypeVar("T2_co", covariant=True)


class P1Parent(Protocol[T2_co]):
    def f0(self, /) -> Self:
        ...


class P1Child(P1Parent[T2_co], Protocol[T2_co]):
    ...


class C1(Generic[T1_co]):
    def f0(self, /) -> Self:
        return self


a1: P1Parent[str] = C1[str]()
b1: P1Child[str] = C1[str]()


class P2Parent(Protocol[T1_co]):
    def f0(self, right: Self, /) -> "P2Parent[T1_co]":
        return right


class P2Child(P2Parent[T1_co], Protocol[T1_co]):
    ...


class C2(Generic[T2_co]):
    def f0(self, other: Self) -> "C2[T2_co]":
        return other


a2: P2Parent[str] = C2[str]()  # OK
b2: P2Child[str] = C2[str]()  # OK