Python 类型标注如何地道地指明某类型为 comparable/orderable?

2021-01-02 00:58:44 +08:00
 littleMaple

例如如下可复现例子:

from typing import TypeVar

T = TypeVar("T")

def is_bigger(a: T, b: T)->bool:
    return a > b

类型检查库 Pyright 报错如下:

Operator ">" not supported for types "T" and "T"

类型检查库 MyPy 报错如下:

Unsupported left operand type for > ("T")
1704 次点击
所在节点    Python
4 条回复
ericls
2021-01-02 01:14:38 +08:00
给一个 `__lt__`
Trim21
2021-01-02 01:36:02 +08:00
littleMaple
2021-01-02 02:15:14 +08:00
@Trim21 正解,谢谢大佬!看来使用 Python 类型标注需要额外封装的东西也不少啊 😂
abersheeran
2021-01-02 16:06:18 +08:00
@littleMaple 是的。还需慢慢发展。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/740978

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX