如何使用Python结构化模式匹配检测hashable(可哈希)类型实例
正确匹配可哈希类型实例的case分支写法
你原有代码的错误原因是:Python中不可哈希的类型并不是没有__hash__属性,而是会将该属性显式设置为None,所以仅判断__hash__属性存在的逻辑必然会匹配所有对象。
以下是两种可用的实现方案:
方案1:使用collections.abc.Hashable抽象基类匹配
这是最简洁的写法,直接匹配可哈希类型的实例,不需要额外自定义判断逻辑:
from collections.abc import Hashable for obj in [], (), set(), frozenset(), 10, None, dict(): match obj: case Hashable(): print('Hashable type: ', type(obj)) case _: print('Unhashable type: ', type(obj))
运行后输出正确结果:
Unhashable type: <class 'list'> Hashable type: <class 'tuple'> Unhashable type: <class 'set'> Hashable type: <class 'frozenset'> Hashable type: <class 'int'> Hashable type: <class 'NoneType'> Unhashable type: <class 'dict'>
方案2:使用属性匹配+守卫判断__hash__不为None
如果你不想额外导入抽象基类,可以在原有写法基础上增加守卫,校验__hash__的值不为None即可:
for obj in [], (), set(), frozenset(), 10, None, dict(): match obj: case object(__hash__=h) if h is not None: print('Hashable type: ', type(obj)) case _: print('Unhashable type: ', type(obj))
该写法的输出和方案1完全一致。
内容的提问来源于stack exchange,提问作者Raymond Hettinger
相关产品推荐
相关产品推荐

