What happens when you define __eq__ without __hash__?hard

Type
conceptual
Topic
OOP & dunders
Frequency
common
Tags
dunder, hash, OOP, dict
Answer

Python automatically sets __hash__ = None, making instances unhashable — they can't be used as dict keys or set members.

Explanation

The invariant is: if a == b, then hash(a) == hash(b). Without a custom __hash__, Python can't guarantee this, so it makes the class unhashable. Fix: define __hash__ using the same fields that determine equality — return hash((self.x, self.y)). If the object is mutable, it generally shouldn't be hashable — mutating it would break dictionary lookups.

Follow-upWhy should mutable objects generally not be hashable?