cmp function removed in Python 3
suggest changeIn 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 the cmp() functionality, you could use the expression (a > b) - (a < b) as the equivalent for cmp(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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents