In Python 3 the cmp
built-in function was removed, together with the __cmp__
special method.
From the documentation:
The
cmp()
function should be treated as gone, and the__cmp__()
special method is no longer supported. Use__lt__()
for sorting,__eq__()
with__hash__()
, and other rich comparisons as needed. (If you really need thecmp()
functionality, you could use the expression(a > b) - (a < b)
as the equivalent forcmp(a, b)
.)
Moreover all built-in functions that accepted the cmp
parameter now only accept the key
keyword only parameter.
In the functools
module there is also useful function cmp_to_key(func)
that allows you to convert from a cmp
-style function to a key
-style function:
Transform an old-style comparison function to a key function. Used with tools that accept key functions (such as
sorted()
,min()
,max()
,heapq.nlargest()
,heapq.nsmallest()
,itertools.groupby()
). This function is primarily used as a transition tool for programs being converted from Python 2 which supported the use of comparison functions.