Python判断对象是否可以hash

1,203 阅读1分钟
  1. 直接调用__hash__(),但是如果对象的__hash__是None,有可能报错TypeError: 'NoneType' object is not callable。可以加个try捕获异常,不过不够优雅。
  2. 用getattr判断__hash__是否是None,None表示该对象不可hash,这个方案不会抛异常。
  3. 另外,hasattr判断__hash__是否存在是不可行,因为所有对象都返回True。

简单的测试逻辑

d = {
    'a': 111,
    'b': {},
    'c': 'ddd'
}

a = '111'

for k, v in d.items():
    print(hasattr(v, "__hash__"))
    print(getattr(v, "__hash__"))
    print("======================")

输出:
True
<method-wrapper '__hash__' of int object at 0x00007FFD38247050>
======================
True
None
======================
True
<method-wrapper '__hash__' of str object at 0x0000025940693420>
======================