[Python-3000] Need closure on __cmp__ removal
Lars Immisch
lars at ibp.de
Fri Jan 18 23:54:32 CET 2008
Mike Klaas wrote:
> On 18-Jan-08, at 1:37 PM, Lars Immisch wrote:
>>
>> I like cmp, too. I've looked through my code, and I've only used it in
>> script-ish circumstances, but here is an example that sorts a list of
>> files by modification date:
>>
>> def cmp_mtime(f, g):
>> """Too much for a lambda for my tastes."""
>> return cmp(os.stat(f).st_mtime, os.stat(g).st_mtime)
>>
>> files = os.listdir('.')
>> files.sort(cmp_mtime)
>
> The use case of sort-function delegating to cmp() of part of an object
> is covered by the key= parameter, which is faster and more succinct:
>
> files = os.listdir('.')
> files.sort(key=lambda f: os.stat(f).st_mtime)
You are right.
> Grepping though my team's codebase, I see some uses similar to yours
> above, but all can be replaced with key=. Personally, I don't see the
> attraction of writing sort functions this way: I fell in love with key=
> the moment I discovered it.
>
> The relative frequency is 84 key-based sorts to 9 cmp()-based sorts
> (admittedly that is more due to my influence than to a natural
> distribution).
I know off hand how cmp should look like, but with 'key' I think
'attribute access', even if it isn't. My head is stuck with 2.3, it seems.
- Lars
More information about the Python-3000
mailing list