Python › Magic Methods & Operator Overloading
What do __eq__ and __hash__ need to satisfy together, and what happens if you only override __eq__?
IntermediateAnswer
If two objects are equal (__eq__ returns True), they must have the same hash value so they behave consistently in sets and dict keys. By default, defining __eq__ without __hash__ makes the class unhashable (Python sets __hash__ to None automatically), which raises TypeError if you try to put instances in a set or use them as dict keys.
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __eq__(self, other):
return (self.x, self.y) == (other.x, other.y)
def __hash__(self):
return hash((self.x, self.y))
{Point(1,2)} # works because __hash__ is definedReal-world example A caching layer uses custom key objects as dict keys, so their class must define both __eq__ and __hash__ consistently or lookups will fail unpredictably.