Python 2.x breaks cmp() (was Re: A suspected bug)

Huaiyu Zhu hzhu at mars.localdomain
Wed Feb 21 09:02:11 CET 2001


There are two quite different reasons to define order: one is to impose a
meaningful (partial) order, another is to be able to sort things in
(whatever) possible order.

The first reason can be satisfied by rich comparison, using the magic
methods like __lt__, __ge__, and so on.

Can we then use cmp to satisfy the second mativation, namely to put
everything in an order?  This can be done without conflict with the first,
if it is required that __cmp__ be a well order (complete order) compatible
with __lt__.  (Every partial order can be extended to a well order, etc).

Eg, for complex number a+bj, one possibility is to sort them according to
(a,b) and put them between a and a+eps where eps>0.  Another is for
cmp(a,a+bj)==0.  Either would do to avoid exception in sorting.

Now that we have rich comparison, is there any reason, other than
historical, to allow __cmp__ to raise exceptions?  What would happen if sort
just treat exception of cmp(a,b) as cmp(a,b)==0?  Will it go into an
infinite loop?  

Just some random thoughts.

Huaiyu

On Tue, 20 Feb 2001 16:54:26 -0500, Tim Peters <tim.one at home.com> wrote:
>[ssthapa at ntcs-ip45.uchicago.edu, reaffirms the lack of a non-surprising
> ordering for complex numbers]
>
>[Aahz]
>> True enough.  Question is, in the Real World [tm], should everyone who
>> calls list.sort() be forced to wrap in try/except on the chance that a
>> pair of complex numbers will sneak in?
>
>We lost that the instant we let user-defined __cmp__ raise visible
>exceptions; list.sort() simply isn't "safe" anymore regardless of what
>Python does with complex numbers, and we can't go back without again
>ignoring exceptions raised by __cmp__.
>
>You can still define your own comparison function to pass to list.sort(),
>that catches exceptions and hides them, instead supplying whatever ordering
>*you* feel like making up in exceptional cases.  Much slower, though, but
>that's the tradeoff.
>
>In practice, I think I'm going to be more bothered by tuple comparisons.
>For example, I often use bisect.insort() to maintain short lists of tuples
>of the form
>
>    (priority_integer, some_object)
>
>or
>
>    (first_time_to_deal_with_it, some_object)
>
>ordered by the first element.  If there's ever a tie on the first element,
>the builtin lexicographic comparison goes on to compare the second elements.
>I'm sure I'll start getting exceptions due to that.  Again, I'll have to
>wrap some_object in a class with a __cmp__ that hides those exceptions.
>
>afraid-it's-clearly-more-pythonic-not-to-suppress-exceptions-by-
>    magic-ly y'rs  - tim
>
>


-- 
Huaiyu Zhu   <hzhu at users.sourceforge.net>



More information about the Python-list mailing list