询问“是否可散列"?关于Python值 [英] Asking "is hashable" about a Python value

查看:87
本文介绍了询问“是否可散列"?关于Python值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有兴趣接受一个任意的字典并将其复制到一个新的字典中,并在此过程中对其进行变异.

I am interested in taking an arbitrary dict and copying it into a new dict, mutating it along the way.

我想做的一个突变是交换键和值.不幸的是,某些价值观本身就是命令.但是,这会生成无法散列的类型:'dict'"错误.我真的不介意将值字符串化并提供它的密钥.但是,我希望能够执行以下操作:

One mutation I would like to do is swap keys and value. Unfortunately, some values are dicts in their own right. However, this generates a "unhashable type: 'dict'" error. I don't really mind just stringifying the value and giving it the key. But, I'd like to be able to do something like this:

for key in olddict:
  if hashable(olddict[key]):
    newdict[olddict[key]] = key
  else
    newdict[str(olddict[key])] = key

是否有一种干净的方法来做到涉及捕获异常并为"unhashable type"解析消息字符串?

Is there a clean way to do this that doesn't involve trapping an exception and parsing the message string for "unhashable type" ?

推荐答案

从Python 2.6开始,您可以使用抽象基类

Since Python 2.6 you can use the abstract base class collections.Hashable:

>>> import collections
>>> isinstance({}, collections.Hashable)
False
>>> isinstance(0, collections.Hashable)
True

__hash__ .

这样做意味着在程序尝试检索其哈希值时,该类的实例不仅会引发适当的TypeError,而且在检查isinstance(obj, collections.Hashable)时,它们也将被正确标识为不可哈希(不同于定义其实例的类).拥有自己的__hash__()来显式提高TypeError).

Doing so means that not only will instances of the class raise an appropriate TypeError when a program attempts to retrieve their hash value, but they will also be correctly identified as unhashable when checking isinstance(obj, collections.Hashable) (unlike classes which define their own __hash__() to explicitly raise TypeError).

这篇关于询问“是否可散列"?关于Python值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆