Guido rethinking removal of cmp from sort method

MRAB python at mrabarnett.plus.com
Thu Mar 24 20:39:53 EDT 2011


On 24/03/2011 23:49, Steven D'Aprano wrote:
> On Thu, 24 Mar 2011 17:47:05 +0100, Antoon Pardon wrote:
>
>> However since that seems to be a problem for you I will be more
>> detailed. The original poster didn't ask for cases in which cmp was
>> necessary, he asked for cases in which not using cmp was cumbersome.
>
> I'm the original poster, and that's not what I said. I said:
>
> "If anyone has any use-cases for sorting with a comparison function that
> either can't be written using a key function, or that perform really
> badly when done so, this would be a good time to speak up."
>
> You'll notice that I said nothing about whether writing the code was easy
> or cumbersome, and nothing about readability.
>
>
>> I
>> gave a case where not using cmp was cumbersome. a tuple where you want
>> it sorted with first item in descending order and second item ascending.
>
> No, I'm sorry, calling sort twice is not cumbersome. In fact, if somebody
> gave me code that sorted tuples in that way using a comparison function,
> I would immediately rip it out and replace it with two calls to sort: not
> only is it usually faster and more efficient, but it's easier to read,
> easier to reason about, and easier to write.
>
>
> from operator import itemgetter
> data.sort(key=itemgetter(1))
> data.sort(key=itemgetter(0), reverse=True)
>
If there are two, it isn't too bad, but if there are several (some
ascending, some descending), then it gets a little cumbersome.
>
> A cmp function for this task may have been justified back in the Dark
> Ages of Python 2.2, before Python's sort was guaranteed to be stable, but
> there's no need for it now.
>
[snip]
It's one of those things I wouldn't have voted to remove, but now it's
gone, I'm unsure how much I'd like it back! I wouldn't object to it
returning...



More information about the Python-list mailing list