Separating __cmp__ from < and > ?

Huaiyu Zhu hzhu at localhost.localdomain
Wed Aug 16 14:13:36 EDT 2000


On 15 Aug 2000 00:47:27 GMT, Aahz Maruch <aahz at netcom.com> wrote:
>>In many situations it is conceptually possible to have a!=b without either
>>a<b or a>b.  Mathematically, this is the case for objects that live in a
>>partially ordered space.
>
>Right.  Problem is, though, that if you have a list of such objects and
>someone does list.sort(), you need to have a way of evaluating the sort
>order.  My suggestion to you is that you define a new set of methods for
>these objects.

As two others have pointed out, allowing additional __lt__, __gt__ would not
make __cmp__ worse for use with sort.  In fact, it might make it better.

Say I have a class of objects with equality test given by 

eq(a,b)

but "not eq(a,b)" does not imply "lt(a,b) or gt(a,b)".  Now if I want to use
expressions like a==b or a!=b, I could do

def __cmp__(self, other): return not eq(self, other)

But this may imply "a>b and b>a and not a<b and not b<a", which really
messes up sort and friends.  Instead of faking a well order, it destroys the
partial order.  Examples of this include abs(a-b) for complex numbers, or
more generally, norm(a-b) for matrices.

The only proper way to handle partially ordered but not well ordered class
of objects would be to allow __cmp__(a,b) to return None when indeed there
is no order between a, b.  In that case the default python order would be
used.  This establishes a well order compatible with the given partial
order, and all the functions needing it would behave properly.

More specifically, depending on the return value of a.__cmp__(b):
+n        not a==b and a>b and not a<b
0         a==b and not a>b and not a<b
-n        not a==b and not a>b and a<b
None      not a==b and not a>b and not a<b

Allowing __lt__ and __gt__ could do the same trick, in a more roundabout way
that is still better than current situation.

Huaiyu

PS. I just checked the Rich Comparison PEP and it is empty.  Would it also
suddenly get some contents from nowhere when a discussion reaches some
conclusion?  Maybe this whole PEP business is a ploy to keep outsiders out?
<0.9wink>




More information about the Python-list mailing list