34. Custom Hashable Classes

Here are 10 Python code snippets demonstrating how to implement __hash__ and __eq__ for custom objects, making them hashable and usable in hashable collections like sets and dictionaries.


1. Basic Hashable Class

This example shows how to create a simple custom class that is hashable.

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))

# Create instances
p1 = Person("Alice", 30)
p2 = Person("Alice", 30)

# Use in a set
people = {p1, p2}
print(len(people))  # Output: 1, since p1 and p2 are considered equal

2. Hashable with Mutable Fields

This class demonstrates a hashable object with mutable fields but ensures the hash remains valid.


3. Using frozenset for Nested Objects

Here’s a hashable class with a frozenset that makes it immutable.


4. Hashable with Tuple Field

Using a tuple as an argument to make an object hashable.


5. Hashable with __slots__

An optimized version of a class using __slots__ for better memory usage.


6. Hashable with Multiple Attributes

Creating a hashable object with more than two attributes.


7. Custom Hashing Algorithm

You can use a custom hashing algorithm.


8. Handling Mutable and Immutable Types Together

This example involves a class where one of the attributes is mutable.


9. Immutable Class with NamedTuple

Using namedtuple to create a hashable class with named fields.


10. Custom Hash with Cache

In this example, a cache is used to optimize repeated hash computations.


These snippets show various ways to implement __hash__ and __eq__ for custom objects, ensuring they can be used in hashable collections like sets and dictionaries. Each example tackles different use cases, such as immutable fields, mutable fields, and caching for optimization.

Last updated