Maintain Equality and Hashing Contracts
Core idea
__eq__ defines equality for a custom type. If two hashable objects compare equal, their hashes must be equal; the reverse need not hold. A hash must remain stable during the object’s lifetime. When a class defines eq without hash, Python normally makes it unhashable. For mutable value-based objects that is useful. For hashable value objects, prevent changes to equality-relevant state. The example uses an immutable tuple subclass with empty slots (no instance attribute dictionary).
class Key(tuple): __slots__ = () def __hash__(self): return hash(tuple(self))a = Key(("A", 3))b = Key(("A", 3))print(a == b, hash(a) == hash(b))print(len({a, b}))The subclass inherits tuple equality and delegates hashing to a tuple of the same members, preserving equality with ordinary tuples. Its members here are immutable strings and integers.
Mutable equality without hashing
class Reading: def __init__(self, value): self.value = value def __eq__(self, other): if not isinstance(other, Reading): return NotImplemented return self.value == other.valuea = Reading(5)print(a == Reading(5), Reading.__hash__ is None)NotImplemented lets Python try the other operand; defining equality disables the inherited default hash.
Intentional failure: unhashable key
class Reading: def __eq__(self, other): return isinstance(other, Reading)print(hash(Reading()))The class has equality but no hash implementation.
Common mistake
Do not add object.__hash__ to a value-equality class merely to enable dictionary keys: distinct equal objects could have different identity-based hashes. Hash collisions are valid and hashes are not persistent IDs.
Practice
Compare equal Key instances as dictionary keys; then try a mutable Reading as a key and explain the error.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Equality and hashing
Check your understanding of equality and hashing.
What is printed?
a = (2, "B")b = (2, "B")print(hash(a) == hash(b), len({a, b}))What is printed?
class Item: def __eq__(self, other): return isinstance(other, Item)print(Item.__hash__ is None)What happens?
class Item: def __eq__(self, other): return isinstance(other, Item)print(len({Item()}))Which statement describes a valid hash contract?