Custom Equality with eq and hash

Learn how to implement custom equality and hashing in Python using __eq__ and __hash__ for object comparison and usage in sets or dictionaries.
Custom Equality and Hashing in Python with __eq__ and __hash__
In Python, objects are compared using their memory addresses by default. This means two instances of the same class with identical data will not be considered equal unless you override the default behavior. To define what equality means for your objects, you can implement the __eq__
method. Similarly, to make objects usable in hashed collections like set
and as dict
keys, you also need to define __hash__
.
Why Customize Equality?
By default, the ==
operator checks whether two objects are the same instance. In many applications, we want equality to mean equivalence of values or attributes, not object identity. For example, two Person
objects with the same name and age should compare as equal.
Implementing __eq__
The __eq__(self, other)
method allows you to define custom comparison logic between instances of a class. Here is an example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __eq__(self, other):
if isinstance(other, Person):
return self.name == other.name and self.age == other.age
return False
This method checks whether other
is a Person
and then compares their attributes.
Implementing __hash__
For objects to be used in sets or as keys in dictionaries, they must be hashable. A hashable object must have an unchanging __hash__
value during its lifetime and must also define __eq__
. Here’s how to add a hash function:
def __hash__(self):
return hash((self.name, self.age))
The tuple of attributes is passed to hash()
to produce a combined hash value.
Example: Using Custom Objects in Sets
Once __eq__
and __hash__
are implemented, you can use your objects in sets and as dictionary keys.
p1 = Person(\\"John\\", 30)
p2 = Person(\\"John\\", 30)
p3 = Person(\\"Bob\\", 25)
people = p1, p3
print(p2 in people) # Output: True
Here, p2
is considered equal to p1
because their attribute values are the same.
Best Practices
- Always implement
__hash__
if you implement__eq__
. - Use immutable attributes for hashing to avoid unexpected behavior in sets and dicts.
- Be cautious when overriding these methods as incorrect implementations can break collection behaviors.
Conclusion
Custom equality and hashing enable you to make Python objects behave like primitive types in comparisons and hashed collections. Mastering __eq__
and __hash__
is crucial for developing clean and robust object-oriented code in Python.
Subscribe to Our YouTube for More
https://blog.arashtad.com/updates/custom-equality-with-eq-and-hash/?feed_id=11986&_unique_id=687ca07a92608
Comments
Post a Comment