How to Implement __hash__ in Python: Simple Guide
To implement
__hash__ in Python, define the method inside your class to return an integer hash value representing the object. This allows instances to be used as keys in dictionaries or stored in sets. Make sure that objects that compare equal have the same hash value.Syntax
The __hash__ method is defined inside a class and must return an integer. This integer is the hash value of the object.
def __hash__(self):— method header- Return an integer representing the object’s hash
python
class MyClass: def __hash__(self): # return an integer hash value return 42
Example
This example shows a class with __hash__ implemented based on its attributes. It allows objects to be used as dictionary keys.
python
class Person: def __init__(self, name, age): self.name = name self.age = age def __eq__(self, other): if not isinstance(other, Person): return False return self.name == other.name and self.age == other.age def __hash__(self): return hash((self.name, self.age)) # Create two identical persons p1 = Person('Alice', 30) p2 = Person('Alice', 30) # Use as dictionary keys people = {p1: 'Engineer'} print(people[p2]) # Output: Engineer
Output
Engineer
Common Pitfalls
Common mistakes when implementing __hash__ include:
- Not defining
__eq__consistently with__hash__. Objects that compare equal must have the same hash. - Using mutable attributes in the hash calculation, which can cause errors if the object changes after hashing.
- Returning non-integer values from
__hash__.
python
class BadPerson: def __init__(self, name): self.name = name def __eq__(self, other): return self.name == other.name def __hash__(self): # Wrong: returns a string instead of int return self.name # Correct way class GoodPerson: def __init__(self, name): self.name = name def __eq__(self, other): return self.name == other.name def __hash__(self): return hash(self.name)
Quick Reference
- Define
__hash__(self)to return an int. - Ensure
__eq__and__hash__are consistent. - Use only immutable attributes in hash calculation.
- Use Python’s built-in
hash()function on tuples of attributes.
Key Takeaways
Implement __hash__ to return an integer hash value for your object.
Ensure __hash__ and __eq__ are consistent: equal objects must have the same hash.
Use only immutable attributes to compute the hash to avoid errors.
Use Python’s built-in hash() on tuples of attributes for simplicity.
Objects with __hash__ can be used as dictionary keys and in sets.