[Python-3000] Total ordering and __cmp__

Adam Olsen rhamph at gmail.com
Wed Mar 21 20:47:55 CET 2007


On 3/20/07, Steven Bethard <steven.bethard at gmail.com> wrote:
> On 3/20/07, Collin Winter <collinw at gmail.com> wrote:
> > Quoting from the commit message for r51533, which removed the default ordering:
> >
> > """
> > A general problem with getting lots of these tests to pass is
> > the reality that for object types that have a natural total ordering,
> > implementing __cmp__ is much more convenient than implementing
> > __eq__, __ne__, __lt__, and so on.  Should we go back to allowing
> > __cmp__ to provide a total ordering?  Should we provide some other
> > way to implement rich comparison with a single method override?
> > Alex proposed a __key__() method
>
> I've used a __key__() method quite successfully in my own code.  Maybe
> we should provide a mixin like::
>
>     class KeyedComparisonMixin(object):
>         def __eq__(self, other):
>             return self.__key__() == other.__key__()
>         def __ne__(self, other):
>             return self.__key__() != other.__key__()
>         def __lt__(self, other):
>             return self.__key__() < other.__key__()
>         def __le__(self, other):
>             return self.__key__() <= other.__key__()
>         def __gt__(self, other):
>             return self.__key__() > other.__key__()
>         def __ge__(self, other):
>             return self.__key__() >= other.__key__()
>
> That way, any classes that needed __cmp__-like behavior could request
> it explicitly by using the mixin.  (If people really want it, we could
> define a __cmp__-based mixin instead, but I've *always* found the
> __key__-based mixin to be a better approach in my own code.)

This seems to match what I've usually needed, but I'm not sure it's
worth putting in python proper.  How about a cookbook entry?  It would
also be nice to reference in a guide on making code 3.0-ready.

-- 
Adam Olsen, aka Rhamphoryncus


More information about the Python-3000 mailing list