You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 01:27:06