Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an object properly hashable?

Here is my code:

class Hero:     def __init__(self, name, age):         self.name = name         self.age = age      def __str__(self):         return self.name + str(self.age)      def __hash__(self):         print(hash(str(self)))         return hash(str(self))  heroes = set()  heroes.add(Hero('Zina Portnova', 16)) # gets hash -8926039986155829407 print(len(heroes)) # gets 1  heroes.add(Hero('Lara Miheenko', 17)) # gets hash -2822451113328084695 print(len(heroes)) # gets 2  heroes.add(Hero('Zina Portnova', 16)) # gets hash -8926039986155829407 print(len(heroes)) # gets 3! WHY? 

Why is this happening?
The 1st and the 3rd object have same content and same hash but len() tells about 3 unique objects?

like image 509
Denis Kreshikhin Avatar asked Jun 12 '12 09:06

Denis Kreshikhin


People also ask

How do I make a hashable object in Python?

An object hash is an integer number representing the value of the object and can be obtained using the hash() function if the object is hashable. To make a class hashable, it has to implement both the __hash__(self) method and the aforementioned __eq__(self, other) method. As with equality, the inherited object.

What does it mean for an object to be hashable?

An object is said to be hashable if it has a hash value that remains the same during its lifetime.

Does hashable mean immutable?

Hashable. 00:00 Immutable objects are a type of object that cannot be modified after they were created. Hashable objects, on the other hand, are a type of object that you can call hash() on.

What kind of data is considered hashable?

Hashable data types: int , float , str , tuple , and NoneType . Unhashable data types: dict , list , and set .


1 Answers

You also need to define __eq__() in a compatible way with __hash__() – otherwise, equality will be based on object identity.

On Python 2, it is recommended you also define __ne__ to make != consistent with ==. On Python 3, the default __ne__ implementation will delegate to __eq__ for you.

like image 70
Sven Marnach Avatar answered Sep 16 '22 15:09

Sven Marnach