如何指定必须满足多个协议的对象?例如,假设我需要一个同时满足Reversible
和Iterable
的对象:
from typing import Iterable, Reversible
l = [1, 2, 3]
r: Reversible[int] = l
i: Iterable[int] = l
reversed(r) # fine
iter(i) # fine
reversed(i) # err since not iterable
iter(r) #err since not reversible
我想以某种方式注释一个变量,其中所有操作都是可能的。例如(编造语法(:
T = TypeVar('T')
ReversibleIterable = Intersection[Reversible[T], Iterable[T]]
ri: ReversibleIterable[int] = l
reversed(ri) # fine
iter(ri) # fine
这样的事情存在吗?我使用协议、有界 TypeVar 等搜索变通方法,但无法使其工作。
ReversibleIterable = Intersection[Reversible[T], Iterable[T]]
有一个关于交叉点类型的旧开放提案:typeping#213。到目前为止还没有批准。
我使用协议搜索
解决方法
您确实可以引入自己的交集协议:
_T_co = TypeVar("_T_co", covariant=True)
class ReversibleIt(Reversible[_T_co], Iterable[_T_co], Protocol[_T_co]):
pass
r: ReversibleIt[int] = [1, 2, 3]