Back to results for “Comprehensions & Generators”
Python › functools & Functional Programming Tools

How does functools.cmp_to_key bridge old-style comparison functions with Python 3's key-based sorting?

Advanced

Answer

Python 3 removed the cmp parameter from sorted() and list.sort() in favor of key functions. cmp_to_key wraps a legacy two-argument comparison function (returning negative, zero, or positive) into a key-function-compatible object, letting you reuse comparator logic (e.g., from Python 2 code or complex multi-field tie-breaking) with modern sorting.
from functools import cmp_to_key

def compare(a, b):
    if a['priority'] != b['priority']:
        return b['priority'] - a['priority']
    return a['name'] < b['name'] and -1 or 1

items = [{'name':'b','priority':1}, {'name':'a','priority':2}]
sorted_items = sorted(items, key=cmp_to_key(compare))
Real-world example A task queue with complex tie-breaking rules (priority descending, then name ascending) uses cmp_to_key to port an existing comparator into sorted().

Common follow-ups: Why did Python 3 remove the cmp argument?;When is a plain key function simpler than cmp_to_key?