【问题标题】:Combining several structural types in python在python中组合几种结构类型
【发布时间】:2020-10-19 16:03:04
【问题描述】:

如何指定必须满足多个协议的对象?例如,假设我需要一个同时满足ReversibleIterable 的对象:

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 等搜索了解决方法,但无法使其工作。

【问题讨论】:

    标签: python types type-hinting mypy


    【解决方案1】:

    ReversibleIterable = Intersection[Reversible[T], Iterable[T]]

    有一个关于交叉路口类型的旧公开提案:typing#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]
    

    【讨论】:

    • 有效,但需要 3.7 (typing_extensions) 或 3.8 (typing)。带有输入扩展的 3.6 会引发运行时错误 TypeError: Protocols can only inherit from other protocols, got typing.Reversible
    • 嗯,cannot reproduce thatmypy/typing-extension你安装了哪些版本?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-10
    • 2020-12-30
    • 1970-01-01
    • 2013-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多