Python 3.0, rich comparisons and sorting order

Alex Martelli aleaxit at yahoo.com
Thu Sep 23 09:28:05 EDT 2004


Steven Bethard <steven.bethard at gmail.com> wrote:
   ...
> > today, there are 4 different ways to customize sorting behavior:
> > 
> > 1) passing a comparison function to sort();
> > 2) passing a key generation function to sort();
> > 3) implementing __cmp__;
> > 4) implementing rich comparison methods. 
> 
> There are things you can do with the cmp keyword arugment that you can't do
> with the key keyword argument...  Though I'm not sure how many of these things
> that you *can* do you actually *want* to do...

Considering that key= can be any kind of callable, I don't think it's
true that there are things you can do with cmp= that you can't do with
key=, taking the argument to the letter.  Consider, for example
(warning: untested...):

def masquerade_a_cmp_as_a_key(acmp):
    class called_as_key(object):
        def __init__(self, obj): self.obj = obj
        def __cmp__(self, other): return acmp(self.obj, other.obj)
    return called_as_key

now, anylist.sort(key=masquerade_a_cmp_as_a_key(foo)) should do just the
same thing (albeit a tad slower) as anylist.sort(cmp=foo), I believe.


Alex



More information about the Python-list mailing list