__eq__
__eq__ defines value equality for a custom type. State explicitly which fields make two instances equivalent.
Understand the idea
Return NotImplemented for unsupported comparison types so Python can try the other operand's comparison rules. Equality should behave consistently with your object's intended identity. Defining equality also affects hashability: mutable objects with value equality generally should not pretend to have an unrelated stable hash. A frozen dataclass can help for suitable immutable values.
Where to try it
Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.
A worked example
class SeatCount:
def __init__(self, value):
self.value = value
def __eq__(self, other):
if not isinstance(other, SeatCount):
return NotImplemented
return self.value == other.value
print(SeatCount(3) == SeatCount(3))
Read the result
The result is True even though the two instances are distinct objects.
Try one change
Compare equality with is for two separate instances and explain why the answers differ.