Guido rethinking removal of cmp from sort method

Antoon Pardon Antoon.Pardon at rece.vub.ac.be
Tue Mar 29 03:52:40 EDT 2011


On Mon, Mar 28, 2011 at 11:35:09AM +0000, Steven D'Aprano wrote:

> [...]
> > Forcing people to use a key-function, will produce cases where python
> > will ask for more memory and take longer to sort, than allowing to
> > provide a cmp function.
> 
> More memory yes; take longer to sort, almost certainly not (except, 
> perhaps, for a very narrow window where the addition of a key causes the 
> application to page out to virtual memory, but a comparison function 
> wouldn't -- and even then, the key function might still be faster).
> 
> But we've already covered the "more memory" angle to death. We already 
> understand that. This is why I have asked if there are any *other* use-
> cases for a comparison function.
> 
> Dan Stromberg has suggested that another use-case would be lazy-
> comparisons, where you might not be able to generate a single key 
> cheaply, but you can perform a comparison lazily.
> 
> 
> > This for the simple reason that for some
> > order-functions, the only way to write a key-function will be to write a
> > specific class, that will implement the order with the same kind of code
> > that otherwise would have been put in the cmp function, 
> 
> There is a recipe for that on ActiveState's website, google for 
> cmp_to_key. That recipe has been added to Python's standard library for 
> version 3.2. Please stop flogging that dead horse.

This doesn't make any sense. As far as I can see there is nothing in Dan's
code that would make it more troublesome to use with cmp_to_key than Carl
Bank's examples or that would make it loose more speed than the overhead
I was describing.

Whatever is meant by lazily, the cmp_to_key function will generate a key
function that during the sorting will finally defer to this cmp-function
to do the comparisons. If the cmp is lazy when it does its work as a
cmp-argument, it will be lazy when it does its work when a key is wrapped
around it.

This argument works for whatever property, the cmp-function should posses.
If your cmp argument has property foo when comparing during a sort then
using cmp_to_key will preserve than property when comparing during a sort.
This for the simple reason that with a cmp_to_key function when the
sort comapares two keys, it will after some overhead just call the cmp
function with the undecorated data.

That means that asking for use cases that fall outside the overhead in
memory or speed of the cmp_to_key function and are not about the cumbersome
work in writing your own key-function in order to reduce that overhead,
that asking for such use cases is like asking for a real number that squares
to a negative. We can conclude a priori that there won't be any.

That is why I don't consider a request for such use cases a serious request.



More information about the Python-list mailing list