定义 `__eq__` 的类型是不可散列的吗? [英] Types that define `__eq__` are unhashable?

查看:37
本文介绍了定义 `__eq__` 的类型是不可散列的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在将功能移植到我的程序的 Python 3.1 分支时,我遇到了一个奇怪的错误.我将其缩小为以下假设:

与 Python 2.x 不同的是,在 Python 3.x 中,如果一个对象有一个 __eq__ 方法,它就会自动不可散列.

这是真的吗?

以下是 Python 3.1 中发生的事情:

<预><代码>>>>O类(对象):... def __eq__(self, other):...返回随便"...>>>o = O()>>>d = {o: 0}回溯(最近一次调用最后一次):文件<pyshell#16>",第 1 行,在 <module> 中d = {o: 0}类型错误:不可哈希类型:'O'

接下来的问题是,我该如何解决我的个人问题?我有一个对象 ChangeTracker ,它存储一个 WeakKeyDictionary 指向几个对象,为每个对象提供过去某个时间点的泡菜转储值.每当签入现有对象时,更改跟踪器都会说明其新泡菜是否与旧泡菜相同,因此会说明该对象在此期间是否已更改.问题是,现在我什至无法检查给定的对象是否在库中,因为它会引发关于对象不可散列的异常.(因为它有一个 __eq__ 方法.)我该如何解决这个问题?

解决方案

是的,如果定义了__eq__,则默认__hash__(即对对象地址进行hash在内存中)消失.这很重要,因为散列需要与相等一致:相等的对象需要散列相同.

解决方案很简单:只需定义 __hash__ 和定义 __eq__.

I had a strange bug when porting a feature to the Python 3.1 fork of my program. I narrowed it down to the following hypothesis:

In contrast to Python 2.x, in Python 3.x if an object has an __eq__ method it is automatically unhashable.

Is this true?

Here's what happens in Python 3.1:

>>> class O(object):
...     def __eq__(self, other):
...         return 'whatever'
...
>>> o = O()
>>> d = {o: 0}
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    d = {o: 0}
TypeError: unhashable type: 'O'

The follow-up question is, how do I solve my personal problem? I have an object ChangeTracker which stores a WeakKeyDictionary that points to several objects, giving for each the value of their pickle dump at a certain time point in the past. Whenever an existing object is checked in, the change tracker says whether its new pickle is identical to its old one, therefore saying whether the object has changed in the meantime. Problem is, now I can't even check if the given object is in the library, because it makes it raise an exception about the object being unhashable. (Cause it has a __eq__ method.) How can I work around this?

解决方案

Yes, if you define __eq__, the default __hash__ (namely, hashing the address of the object in memory) goes away. This is important because hashing needs to be consistent with equality: equal objects need to hash the same.

The solution is simple: just define __hash__ along with defining __eq__.

这篇关于定义 `__eq__` 的类型是不可散列的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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