Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Types that define `__eq__` are unhashable?

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?

like image 339
Ram Rachum Avatar asked Oct 22 '09 17:10

Ram Rachum


People also ask

What are Unhashable types?

Unhashable type errors appear in a Python program when a data type that is not hashable is used in code that requires hashable data. An example of this is using an element in a set or a list as the key of a dictionary.

What does Unhashable mean?

"unhashable" means it cannot be used to build hash. Dictionaries use hash-functions to speed up access to values through keys.

Why are lists Unhashable?

The “TypeError: unhashable type: 'list'” error is raised when you try to assign a list as a key in a dictionary. To solve this error, ensure you only assign a hashable object, such as a string or a tuple, as a key for a dictionary.

What does Unhashable type set mean in Python?

The Python "TypeError: unhashable type: 'set'" occurs when we use a set as a key in a dictionary or an element in another set . To solve the error, use a frozenset instead, because set objects are mutable and unhashable.


1 Answers

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__.

like image 55
Martin v. Löwis Avatar answered Sep 28 '22 04:09

Martin v. Löwis