
在python中,某些数据结构(如集合的元素、字典的键)要求其内容是“可哈希的”(hashable)。一个对象可哈希意味着它有一个不变的哈希值,并且在生命周期内哈希值不会改变。这通常通过实现__hash__方法和__eq__方法来体现。typing模块提供了hashable抽象基类,用于类型提示。
另一方面,当我们需要对对象进行排序时,这些对象必须是“可排序的”(Orderable)。这意味着它们需要支持一系列比较操作,例如小于(__lt__)、小于等于(__le__)、等于(__eq__)、不等于(__ne__)、大于(__gt__)和大于等于(__ge__)。Python内置的sorted()函数或列表的sort()方法都依赖于这些比较方法来确定元素的顺序。
当一个函数需要一个既可哈希又可排序的参数时,如何为其提供一个准确且富有表达力的类型提示,是我们在编写高质量Python代码时需要解决的问题。
我们可能会尝试使用TypeVar并为其绑定Hashable来表示可哈希性:
from collections.abc import Hashable
from typing import TypeVar
# 这种方式只表达了可哈希性
OrderedHashable = TypeVar('OrderedHashable', bound=Hashable)
def foo(bar: OrderedHashable) -> None:
# 在这里,我们知道bar是可哈希的,但静态分析工具不知道它是否可排序
pass然而,这种方法存在明显的局限性。虽然OrderedHashable这个名字暗示了“有序”,但TypeVar的bound=Hashable仅仅保证了参数是可哈希的,并没有强制要求它实现任何排序相关的魔术方法(如__lt__或__gt__)。因此,静态类型检查工具无法识别bar是否支持比较操作。
为了解决上述问题,Python的typing模块提供了Protocol。Protocol允许我们定义一个结构化的类型,即只要一个类实现了Protocol中定义的所有方法和属性,它就被认为是符合该Protocol的类型,而无需显式继承。这非常适合定义像“可哈希且可排序”这样的复合行为。
我们可以定义一个Protocol,它继承自Hashable,并额外声明__gt__和__lt__方法:
from typing import Hashable, Protocol, TypeVar
# 定义一个Protocol,表示既是可哈希的,又支持排序比较
class OrderedHashable(Hashable, Protocol):
"""
表示一个既可哈希又可排序的类型。
需要实现__hash__、__eq__(来自Hashable)以及__gt__、__lt__方法。
"""
def __gt__(self, other: "OrderedHashable") -> bool:
"""
定义大于操作 (self > other)。
"""
... # 省略具体实现,Protocol中只需声明签名
def __lt__(self, other: "OrderedHashable") -> bool:
"""
定义小于操作 (self < other)。
"""
... # 省略具体实现,Protocol中只需声明签名
# 使用TypeVar绑定这个Protocol,以便在泛型函数中使用
OrderedHashableT = TypeVar('OrderedHashableT', bound=OrderedHashable)
def process_ordered_hashable(item: OrderedHashableT) -> None:
"""
一个接受可排序且可哈希参数的函数。
"""
print(f"处理项: {item}")
# 静态类型检查工具现在知道item支持哈希和比较操作
_ = hash(item) # 可哈希
if item < item: # 可排序
pass
if item > item: # 可排序
pass
# 示例:定义一个符合OrderedHashable协议的类
class MySortableItem:
def __init__(self, value: int, name: str):
self.value = value
self.name = name
def __hash__(self) -> int:
return hash((self.value, self.name))
def __eq__(self, other: object) -> bool:
if not isinstance(other, MySortableItem):
return NotImplemented
return self.value == other.value and self.name == other.name
def __lt__(self, other: "MySortableItem") -> bool:
if not isinstance(other, MySortableItem):
return NotImplemented
return self.value < other.value
def __gt__(self, other: "MySortableItem") -> bool:
if not isinstance(other, MySortableItem):
return NotImplemented
return self.value > other.value
def __repr__(self) -> str:
return f"MySortableItem(value={self.value}, name='{self.name}')"
# 使用示例
item1 = MySortableItem(10, "Apple")
item2 = MySortableItem(20, "Banana")
process_ordered_hashable(item1) # 类型检查通过
process_ordered_hashable(item2) # 类型检查通过
# 尝试使用不符合协议的类型(例如,只可哈希但不可排序)
class JustHashable:
def __init__(self, value: int):
self.value = value
def __hash__(self) -> int:
return hash(self.value)
def __eq__(self, other: object) -> bool:
if not isinstance(other, JustHashable):
return NotImplemented
return self.value == other.value
# process_ordered_hashable(JustHashable(5))
# 上面的代码会在静态类型检查时报错,因为JustHashable没有实现__lt__和__gt__在这个解决方案中:
通过这种方式,我们不仅能够清晰地表达参数的类型要求(既可哈希又可排序),还能让静态类型检查工具在编译时就捕获潜在的类型不匹配错误,显著提升代码的健壮性和可维护性。
以上就是利用Protocol为可排序且可哈希的参数创建精确类型提示的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号