如何为兼具有序性与可哈希性的参数添加类型提示?
实现兼具可哈希性与有序性的类型提示
要明确指定参数同时具备可哈希性(实现__hash__和__eq__)和有序性(实现比较魔术方法如__lt__),可以通过Protocol定义结构类型,再结合TypeVar使用:
实现步骤
- 定义继承自
Hashable的Protocol,在其中声明有序性所需的魔术方法(通常__lt__和__eq__即可覆盖基本有序操作); - 用TypeVar绑定这个自定义Protocol,确保参数同时满足两种特性。
完整代码示例
from collections.abc import Hashable from typing import Protocol, TypeVar, Any # 定义兼具有序性与可哈希性的Protocol class OrderedHashableProtocol(Protocol, Hashable): def __lt__(self, other: Any) -> bool: ... def __eq__(self, other: Any) -> bool: ... # 绑定Protocol的TypeVar,用于函数参数提示 OrderedHashable = TypeVar('OrderedHashable', bound=OrderedHashableProtocol) def foo(bar: OrderedHashable) -> None: # 示例:使用有序性操作 if bar < some_other_value: ... # 示例:使用可哈希性操作(存入集合) my_set = {bar}
补充说明
- 若需要更严格的有序性支持(如
__gt__、__le__等全量比较方法),可在Protocol中添加对应方法声明; - Protocol会在类型检查时验证传入对象是否实现了所有声明的方法,继承
Hashable则确保对象满足可哈希要求; - 直接使用
OrderedHashableProtocol作为参数类型也可行,使用TypeVar的优势是支持泛型推导,比如函数返回输入参数时能保留具体类型信息。
内容的提问来源于stack exchange,提问作者Galen
相关产品推荐
相关产品推荐

