[Python-Dev] Deprecated __cmp__ and total ordering
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:
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...
More information about the Python-Dev