The functools module in Python allows us to create higher-order functions that interact with other functions. The higher-order functions either return other functions or operate on them to broaden the scope of the function without modifying or explicitly defining them.
A callable that returns a value for sorting or ordering is known as a key function or a collation function. A lot of Python functions accept key functions to modify the order or grouping of items. For example, min(), max() etc. A key function takes an argument and returns a value thatโs considered as the sort key.
Any callable that performs the following is called a comparison function.
cmp_to_key functionPython 2 that has reached End of Life supported comparison functions. But now, the comparison functions are deprecated and no longer used. Hence, cmp_to_key is introduced in Python 3 to support the comparison functions in the form of key functions.
functools.cmp_to_key(callable)
The function takes a callable as a parameter.
from filecmp import cmpfrom functools import cmp_to_keyimport randomdef compare(x, y):if x==y: return 0return 1 if x > y else -1randomlist = random.sample(range(10, 30), 5)print("List before sorting - ", randomlist)randomlist.sort(key=cmp_to_key(compare))print("List after sorting - ", randomlist)
compare.randomlist.randomlist is printed before sorting.randomlist is sorted using the sort() method, passing the compare function as the parameter to cmp_to_key.randomlist is printed.