[Python-Dev] decorate-sort-undecorate

Tim Peters tim.one at comcast.net
Tue Oct 14 16:53:17 EDT 2003


[Geoffrey Talvola]
> I disagree... I almost always use DSU in any circumstances because I
> find it easier and more natural to write:
>
> def keyfunc(record):
>     return record.LastName.lower(), record.FirstName.lower(),
>            record.PhoneNumber
> mylist = sortUsingKeyFunc(mylist, keyfunc)

You've left out the body of sortUsingKeyFunc, so I expect you're unusual in
having built up helper routines for doing DSU frequently.

> than to have to write an equivalent comparison function:
>
> def cmpfunc(r1, r2):
>     return cmp((r1.LastName.lower(), r1.FirstName.lower(),
>                r1.PhoneNumber), (r2.LastName.lower(),
>                r2.FirstName.lower(), r2.PhoneNumber))
> mylist.sort(cmpfunc)

This is wordier than need be, though, duplicating code for the purpose of
making it look bad <wink>.  I'd do

mylist.sort(lambda a, b: cmp(keyfunc(a), keyfunc(b)))

> so for me, ease of use is the reason, not speed.  Of course, it
> doesn't _hurt_ that DSU is faster...

If your records often tie on the result of keyfunc (doesn't look likely
given the names you picked here), and your sortUsingKeyFunc() function
doesn't inject the original list index (or otherwise force a cheap
tie-breaker), DSU can be much slower than passing a custom comparison
function.  Not likely, though.




More information about the Python-Dev mailing list