[Python-3000] Total ordering and __cmp__
Steven Bethard
steven.bethard at gmail.com
Wed Mar 21 04:36:28 CET 2007
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.)
STeVe
--
I'm not *in*-sane. Indeed, I am so far *out* of sane that you appear a
tiny blip on the distant coast of sanity.
--- Bucky Katt, Get Fuzzy
More information about the Python-3000
mailing list