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
- Python Context Manager Exception Handling and Retrying.
- BCE architecture is the simplest way to structure your source code files, read all about it in my post on BCE.
- Did you know that you can implement functional ForEach in Bash?