[Python-Dev] Deprecated cmp and total ordering (original) (raw)

Mart Sõmermaa mrts.pydev at gmail.com
Tue Mar 10 13:00:32 CET 2009


cmp used to provide a convenient way to make all ordering operators work by defining a single method. For better or worse, it's gone in 3.0.

To provide total ordering without cmp one has to implement all of lt, gt, le, ge, eq and ne. However, in all but a few cases it suffices only to provide a "real" implementation for e.g. lt and define all the other methods in terms of it as follows:

class TotalOrderMixin(object): def lt(self, other): raise NotImplemented # override this

def __gt__(self, other):
    return other < self

def __le__(self, other):
    return not (other < self)

def __ge__(self, other):
    return not (self < other)

eq and ne are somewhat special, although it is possible to define them in terms of lt

def __eq__(self, other):
    return not (self == other)

def __ne__(self, other):
    return self < other or other < self

it may be inefficient.

So, to avoid the situation where all the projects that match http://www.google.com/codesearch?q=cmp+lang%3Apython have to implement their own TotalOrderMixin, perhaps one could be provided in the stdlib? Or even better, shouldn't a class grow automagic gt, le, ge if lt is provided, and, in a similar vein, ne if eq is provided? -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-dev/attachments/20090310/d0ee96dd/attachment.htm>



More information about the Python-Dev mailing list