Would there be support for a more general cmp/__cmp__

Antoon Pardon apardon at forel.vub.ac.be
Thu Oct 20 12:13:15 CEST 2005

Op 2005-10-20, Mikael Olofsson schreef <mikael at isy.liu.se>:
> Antoon Pardon wrote:
>> Op 2005-10-20, Duncan Booth schreef <duncan.booth at invalid.invalid>:
>>>Antoon Pardon wrote:
>>>>The problem now is that the cmp protocol has no way to
>>>>indicate two objects are incomparable, they are not
>>>>equal but neither is one less or greater than the other.
>>>If that is the case then you implement __eq__ and __ne__ to return 
>>>True/False and make cmp throw an exception. I don't see any need to extend 
>>>the cmp protocol.
>> That is not sufficient. There are domains where an order exists, but not
>> a total order. So for some couples of elements it is possible to say
>> one is less than the other, but not for all such couples.
>> Your solution wouldn't allow for such a case.
> Wouldn't the full power of rich comparisons be enough? See section 3.3.1 
> in Python Reference Manual:
>      http://www.python.org/doc/2.4.2/ref/customization.html
> See methods __lt__, __le__, __eq__, __ne__, __gt__, __ge__.

Sure, but it would also be rather cumbersome. It is not uncommon
that a general compare function which could give you one of
four results: one_less_two, one_equal_two, one_greater_two or
one_unequal_two, wouldn't differ much from each of those six
comparison methods. So you either write about six times the
same code or you have to do something like the following:

  class partial_order:

    def __compare(self, other):
      return ...

    def __lt__(self, other):
      return self.__compare(other) == one_less_two

    def __le__(self, other):
      return self.__compare(other) in [one_less_two, one_equal_two]

    def __eq__(self, other):
      return self.__compare(other) == one_equal_two

    def __ne__(self, other):
      return self.__compare(other) == one_unequal_two

    def __gt__(self, other):
      return self.__compare(other) == one_greater_two

    def __ge__(self, other):
      return self.__compare(other) in [one_greater_two, one_equale_two]

And then you still wouldn't get a usefull result from:

  delta = cmp(e1, e2)

Antoon Pardon

More information about the Python-list mailing list