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

Tim Peters tim.one at home.com
Tue Feb 20 16:54:26 EST 2001


[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





More information about the Python-list mailing list