Vaclav Kosar's face photo
Vaclav Kosar
Software, Machine Learning, & Business

Python functools.cmp_to_key Explained

Understand the functools' comparison function to key function conversion quickly.

Function functools.cmp_to_key documentation is a bit mysterious. In short, function cmp_to_key returns a class that implements comparison methods, which Python then uses to compare any two values. Let’s look at the following snippet.

from functools import cmp_to_key


def compare(x: str, y: str) -> int:
    return int(x) - int(y)


key = cmp_to_key(compare)
print(key)
print(key("10").__lt__(key("11")))

Execution of above prints below.

<functools.KeyWrapper object at 0x7f90d3fe79d0>
true

If you go to the source code, you’ll find that you are getting just a class that implements comparison in a new way.

def cmp_to_key(mycmp):
    """Convert a cmp= function into a key= function"""
    class K(object):
        __slots__ = ['obj']
        def __init__(self, obj):
            self.obj = obj
        def __lt__(self, other):
            return mycmp(self.obj, other.obj) < 0
        def __gt__(self, other):
            return mycmp(self.obj, other.obj) > 0
        def __eq__(self, other):
            return mycmp(self.obj, other.obj) == 0
        def __le__(self, other):
            return mycmp(self.obj, other.obj) <= 0
        def __ge__(self, other):
            return mycmp(self.obj, other.obj) >= 0
        __hash__ = None
    return K

You can read more on sorting in Python docs.

Other Useful Posts

Created on 03 Aug 2022. Updated on: 03 Aug 2022.

Let's connect





Privacy Policy How many days left in this quarter? Twitter Bullet Points to Copy & Paste