77. Custom Hashing for Objects
Here are 10 Python code snippets demonstrating how to implement custom hashing for classes to make them usable in sets and dictionaries:
1. Basic Custom Hashing
Implementing __hash__ and __eq__ for a simple class.
Copy
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __eq__(self, other):
return (self.name, self.age) == (other.name, other.age)
def __hash__(self):
return hash((self.name, self.age))
# Using in set
person1 = Person("Alice", 30)
person2 = Person("Alice", 30)
people = {person1, person2}
print(people) # Only one entry, because Person objects are hashable and equal2. Hashing with Multiple Attributes
Create a custom class with multiple attributes, where __hash__ combines them.
Copy
3. Custom Hash for Mutable Attributes
Make sure to handle mutable attributes carefully, as they can break hash consistency.
Copy
4. Handling Hash Collisions
The __hash__ method must return a unique value for different objects, but sometimes collisions happen.
Copy
5. Using Only Immutable Attributes for Hashing
Using immutable attributes such as tuples for a hash function to guarantee consistency.
Copy
6. Custom Hash with Complex Objects
Custom classes that use complex objects, like dictionaries, for hashing.
Copy
7. Handling Non-Hashable Attributes
If an attribute is not hashable, it's crucial to exclude it from the __hash__ method.
Copy
8. Custom Hashing with String Representation
Using string representations of objects to generate unique hashes.
Copy
9. Custom Hashing with Frozen Set
Using a frozenset for hashing sets or dictionaries with unordered elements.
Copy
10. Debugging Hash and Equality
Make sure to implement __eq__ and __hash__ properly to avoid inconsistencies.
Copy
These examples demonstrate how to implement custom hashing by defining __hash__ and __eq__ methods. For custom objects to work correctly in sets and dictionaries, the hash function must be consistent with equality, and the object attributes used in the hash must be immutable and hashable.
Last updated