Advertisement
Intermediate Python, Magic Methods & Operator Overloading

How do comparison magic methods like __lt__, __le__, __gt__, and __ge__ support custom sorting?

Short answer

Implementing these lets instances be compared with , >= respectively, which sorted() and list.sort() rely on by default (via < comparisons) when no key function is given.

Save Python mock interview
Advertisement
AModel answer
Implementing these lets instances be compared with <, <=, >, >= respectively, which sorted() and list.sort() rely on by default (via < comparisons) when no key function is given. Using @functools.total_ordering, you can define just __eq__ and one of these to get all six comparison methods automatically.
class Task:
    def __init__(self, priority):
        self.priority = priority
    def __lt__(self, other):
        return self.priority < other.priority

tasks = [Task(3), Task(1), Task(2)]
tasks.sort()  # sorts using __lt__
Real-world example
A priority queue of custom Task objects relies on __lt__ so heapq.heappush/heappop can order tasks without needing a separate key function.
Likely follow-ups
  • Why does heapq rely specifically on __lt__?
  • How does total_ordering reduce the boilerplate here?
Related topics