Would there be support for a more general cmp/__cmp__

Ron Adam rrr at ronadam.com
Wed Oct 26 09:16:13 EDT 2005



Antoon Pardon wrote:

> Op 2005-10-25, Steven D'Aprano schreef <steve at REMOVETHIScyber.com.au>:

>>Can somebody remind me, what is the problem Antoon is trying to solve here?
> 
> 
> Well there are two issues. One about correct behaviour and one about
> practicallity.
> 
> The first problem is cmp. This is what the documentation states:
> 
> cmp(x, y)
>     Compare the two objects x and y and return an integer according to
>     the outcome. The return value is negative if x < y, zero if x == y
>     and strictly positive if x > y. 
> 
> The problem is, that if someone implements a partial ordered class,
> with the rich comparisons, cmp doesn't behave correct. It can't
> behave correct because it will always give an number as a result
> and such a number implies one of three relations between two
> elements, but with partial ordered classes, it is possible none
> of these relations exist between those two elements. So IMO cmp
> should be changed to reflect this. This can be done either by cmp
> returning None or UnequalValues.  or by cmp raising UnequalValues
> in such a case.

Instead of changing cmp, why not just have several common versions to 
choose from instead of trying to make one tool do it all?

> The second part is one of practicallity. Once you have accepted cmp,
> should reflect this possibility, it makes sense that the __cmp__
> method should get the same possibilities, so that where it is more
> pratical to do so, the programmer can implement his partial order
> through one __cmp__ method instead of having to write six.
> 
> 
> In my opinion such a change would break no existing code. This
> is because there are two possibilities.
 >
> 1) The user is using cmp on objects that form a total order.
> In such circumstances the behaviour of cmp doesn't change.
> 
> 2) The user is using cmp on objects that don't form a total
> order. In such circumstances cmp doesn't give consistent
> results, so the code is already broken.


Adding complexity to cmp may not break code, but it could probably slow 
down sorting in general.  So I would think what ever improvements or 
alternatives needs to be careful not to slow down existing sorting cases.

Cheers,
    Ron




More information about the Python-list mailing list