[Python-3000] Need closure on __cmp__ removal

Mike Klaas mike.klaas at gmail.com
Fri Jan 18 23:24:01 CET 2008


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)

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).

-Mike


More information about the Python-3000 mailing list