What is the Python counterpart of Java's equals/hashCode rule, and what happens if a class defines only __eq__?
__eq__ and __hash__ must agree: objects that compare equal must have the same hash. A class that defines __eq__ without __hash__ becomes unhashable: using it in a set or as a dict key raises TypeError.
Python's dict and set are hash tables, so they rely on the same rule as Java:
__eq__(self, other)decides equality (the==operator),__hash__(self)returns the hash code (the built-inhash()).
Python guards against the Java mistake. If a class overrides __eq__ but not __hash__, Python sets __hash__ to None, and {p} or d[p] = 1 fails with TypeError: unhashable type. The bug shows up immediately instead of as a silently missing key.
The usual fix hashes a tuple of the same fields __eq__ compares:
def __eq__(self, other):
return isinstance(other, Point) and (self.x, self.y) == (other.x, other.y)
def __hash__(self):
return hash((self.x, self.y))
Only immutable objects should be hashable, for the same reason as in Java. That is why list and dict are unhashable and tuple and frozenset are not. @dataclass(frozen=True) generates matching __eq__ and __hash__.
Go deeper:
Python data model: __hash__ โ the rules for
__hash__, and why defining__eq__alone makes a class unhashable.