Datasets:
File size: 1,501 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 75 76 77 78 79 80 81 82 | """
Tests the handling of recursive protocols.
"""
# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#recursive-protocols
from typing import Generic, Iterable, Never, Protocol, Self, TypeVar, assert_type
T = TypeVar("T")
T_co = TypeVar("T_co", covariant=True)
T_contra = TypeVar("T_contra", contravariant=True)
class Traversable(Protocol):
def leaves(self) -> Iterable["Traversable"]:
...
class SimpleTree:
def leaves(self) -> list["SimpleTree"]:
return []
root: Traversable = SimpleTree() # OK
class Tree(Generic[T]):
def leaves(self) -> list["Tree[T]"]:
return []
def walk(graph: Traversable) -> None:
pass
tree: Tree[float] = Tree()
walk(tree) # OK
class ProtoA(Protocol[T_co, T_contra]):
def method1(self) -> "ProtoA[T_co, T_contra]":
...
@classmethod
def method2(cls, value: T_contra) -> None:
...
class ProtoB(Protocol[T_co, T_contra]):
def method3(self) -> ProtoA[T_co, T_contra]:
...
class ImplA:
def method1(self) -> Self:
return self
@classmethod
def method2(cls, value: int) -> None:
pass
class ImplB:
def method3(self) -> ImplA:
return ImplA()
def method1(self) -> Self:
return self
@classmethod
def method2(cls: type[ProtoB[object, T]], value: list[T]) -> None:
pass
def func1(x: ProtoA[Never, T]) -> T:
raise NotImplementedError
v1 = func1(ImplB())
assert_type(v1, list[int])
|