[Python-Dev] Deprecated __cmp__ and total ordering

Michael Foord fuzzyman at voidspace.org.uk
Tue Mar 10 14:19:43 CET 2009

Hello Mart,

This has been discussed before. Guido was against automatically filling 
in these methods based I think on the fact that this may not be what you 
want - worth searching the archives for.

See here for a class decorator that provides all rich comparison methods 
for classes that only implement one (e.g. __lt__):


Michael Foord

Mart Sõmermaa wrote:
> __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?
> ------------------------------------------------------------------------
> _______________________________________________
> Python-Dev mailing list
> Python-Dev at python.org
> http://mail.python.org/mailman/listinfo/python-dev
> Unsubscribe: http://mail.python.org/mailman/options/python-dev/fuzzyman%40voidspace.org.uk


More information about the Python-Dev mailing list