Loading section...

Custom Comparators: Heap with Complex Objects

Concepts: pyCustomComparator, pyCmpToKey, pyDataclassLt

Default heapq works perfectly with numbers and strings. The moment you want to heap-sort custom objects — a Pipeline object, a QueryResult, an Employee — you need to tell Python how to compare them. There are three approaches: implement __lt__ on the dataclass, use functools.cmp_to_key for complex comparison logic, or wrap everything in (priority_value, counter, object) tuples. Each has tradeoffs. Knowing all three, and knowing which to reach for in an interview, is what separates thorough candidates. Approach 1: dataclass with __lt__ The __lt__ approach is the cleanest for objects you own. Add it explicitly rather than using @dataclass(order=True) unless you want ALL comparison operators generated. Note the field(compare=False) on payload — if the payload is a dict or some non-comparable