Python Rich Comparison Methods Explained
Learn how to implement Python rich comparison methods for custom classes, avoid common pitfalls, and keep your code maintainable.

Python rich comparison methods let you define how custom objects behave with operators like ==, <, <=, >, >=, and !=. Instead of relying on identity comparisons, you can implement __eq__, __lt__, and the rest to give your classes meaningful equality and ordering semantics. This article explains how to implement these methods correctly, avoid common pitfalls, and keep your code maintainable.
The Six Rich Comparison Methods
Python defines six special methods that correspond to the six comparison operators. Each method takes self and other and returns a boolean (or sometimes NotImplemented).
| Method | Operator | Purpose |
|---|---|---|
__eq__ | == | Equality |
__ne__ | != | Inequality |
__lt__ | < | Less than |
__le__ | <= | Less than or equal |
__gt__ | > | Greater than |
__ge__ | >= | Greater than or equal |
The object base class provides default __eq__ and __ne__ behavior based on identity (self is other and self is not other). The ordering methods are not implemented by default on object, so obj1 < obj2 raises a TypeError unless your class defines __lt__ or another ordering method.
Implementing Comparison Operators Manually
Consider a Person class with name and age attributes. If you want to sort a list of people by age, you need to define __lt__ and __eq__. The other ordering methods are not automatically derived from those two, so you must either define them or use a helper. Here is a manual implementation:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __eq__(self, other):
if not isinstance(other, Person):
return NotImplemented
return self.age == other.age
def __lt__(self, other):
if not isinstance(other, Person):
return NotImplemented
return self.age < other.ageWith these two methods, == and < work, and != works by default as the inverse of __eq__. But <=, >, and >= still raise TypeError unless you define __le__, __gt__, and __ge__. For example, p1 <= p2 raises TypeError because __le__ is not implemented. To make the class fully comparable, implement the missing methods manually or use functools.total_ordering.
Using functools.total_ordering to Reduce Boilerplate
The functools.total_ordering class decorator lets you define only __eq__ and one other comparison method (e.g., __lt__), and it fills in the remaining ordering methods for you. The decorator inspects the class and adds the missing methods based on the ones you provide.
from functools import total_ordering
@total_ordering
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __eq__(self, other):
if not isinstance(other, Person):
return NotImplemented
return self.age == other.age
def __lt__(self, other):
if not isinstance(other, Person):
return NotImplemented
return self.age < other.ageNow <=, >, and >= work automatically; != continues to use the default inverse of __eq__ unless you define __ne__ yourself. The decorator uses the provided methods to derive the others. For example, __le__ is implemented as self < other or self == other. This reduces boilerplate and keeps the logic in one place.
However, total_ordering can add overhead because the derived methods call the provided ones, adding another Python function call. For most applications this is negligible; if you are comparing many objects in a hot loop, manual implementations may be faster.
Equality, Hashing, and the __hash__ Contract
When you override __eq__ in a class, Python automatically sets __hash__ to None unless you explicitly define it. This makes instances unhashable, which breaks their use in sets and as dictionary keys. The reason is that equal objects must have the same hash value. If you define equality based on mutable attributes, the hash could change, making the object unusable in hash-based collections.
Therefore, define __hash__ only for effectively immutable objects. A common implementation is to hash the same tuple of attributes used by __eq__.
class Person:
def __init__(self, name, age):
self._name = name
self._age = age
@property
def name(self):
return self._name
@property
def age(self):
return self._age
def __eq__(self, other):
if not isinstance(other, Person):
return NotImplemented
return (self.name, self.age) == (other.name, other.age)
def __hash__(self):
return hash((self.name, self.age))Here, equality is based on name and age, and the hash uses the same tuple. The read-only properties help keep the attributes immutable after construction, which satisfies the contract. If you only need ordering and not hashing, leaving __hash__ as None is acceptable, but be aware that the objects cannot be placed in sets or used as dict keys.
Common Mistakes When Overriding Comparison Methods
One frequent mistake is returning False when comparing to an unrelated type instead of returning NotImplemented. Returning NotImplemented tells Python to try the reflected operation on the other operand, which is the correct way to handle mixed-type comparisons.
def __eq__(self, other):
if not isinstance(other, Person):
return NotImplemented # correct
return self.age == other.ageIf you return False for an incompatible type, you may get misleading behavior. For example, person == 42 would silently return False instead of raising a clear error or deferring to the other type.
Another common mistake is assuming Python will derive all ordering methods from __eq__ and __lt__. If you are not using total_ordering, define __le__, __gt__, and __ge__ explicitly when you need them. Meanwhile, in Python 3, != is by default the inverse of __eq__ unless you define __ne__ yourself, so you usually do not need to write __ne__ manually.
Performance and Maintainability Considerations
When you implement comparison methods, keep the logic simple and avoid expensive operations inside them. Sorting a list calls __lt__ many times, so a method that does heavy computation can slow down the sort significantly. If the comparison depends on a computed value, consider caching that value as an attribute.
Another maintainability concern is consistency. If you change the equality criteria, you must also update the hash function and any other comparison methods that rely on the same attributes. Keeping the logic centralized, for example by using a single _key() method, can reduce the risk of inconsistency.
class Person:
def _key(self):
return (self.name, self.age)
def __eq__(self, other):
if not isinstance(other, Person):
return NotImplemented
return self._key() == other._key()
def __lt__(self, other):
if not isinstance(other, Person):
return NotImplemented
return self._key() < other._key()This pattern makes it clear which attributes participate in comparisons and keeps the logic in one place.
Using Dataclasses for Automatic Comparison
If your class primarily stores data, the @dataclass decorator can generate comparison methods for you. By default, dataclasses implement __eq__ and __repr__, and you can enable ordering with order=True.
from dataclasses import dataclass
@dataclass(order=True)
class Person:
name: str
age: intThis generates the comparison methods based on the fields in declaration order. The generated __lt__ compares name first, then age. If you need a different ordering, you can set order=False and implement the methods manually, or use a field that sorts correctly.
Dataclasses also handle __hash__ in a specific way: with the default eq=True and frozen=False, the class is unhashable. If you set frozen=True, the generated class is hashable. This aligns with the hash contract and saves you from writing boilerplate.
For simple data containers, dataclasses are often the most maintainable option. They reduce the amount of code you need to write and make the intent clear. For classes with more complex behavior, manual implementation or total_ordering gives you finer control.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.