Q: sort's key and cmp parameters

Raymond Hettinger python at rcn.com
Tue Oct 6 21:28:00 CEST 2009

> I love the 'key', it makes my code simpler and it's simpler to
> understand. I am not opposed to the idea of keeping cmp, that in some
> rare cases may be useful or more natural.
> The problem is that if you allow to use the cmp, lot of programmers
> will use it straight away, not even bothering to know what that
> strange 'key' argument may be useful for. And they miss the how much
> handy 'key' is.
> So a funny solution to this situation may be the following: to keep
> only 'key' in the sort/sorted for few years, so the community of
> Python programmers gets used to 'key' only, and then put 'cmp' back
> in, for the special cases ;-)

FWIW, sorting is only a small part of the picture.  The notion of
three-way cmp functions was removed throughout the language.  The
built-in cmp() function and the __cmp__ magic method and the
corresponding C slot were all excised.  None of them played nicely
with rich comparisons.  It was a case where having two-ways-to-do-it
was complicating everyone's lives.  AFAICT, very few people understood
exactly how the two interacted -- the under-the-hood C code for it
was complex, unattractive, and hard to understand.

> I am having a very hard type (despite my implementation,
> explanations, etc) explaining to D programmers why for a
> flexible general-purpose function a key function argument
> is often better.

Last week, I learned a new term, "Code Prion", that referred to
a code technique such as cmp-functions which cause the proteins
of the brain to become contagiously misfolded so that the victim
1) always prefers that technique, 2) easily infects others, and
3) is resistant to sterilization (using other techniques) ;-)

Once Kernighan and Ritchie put C's qsort() into the food supply,
we were doomed.

FWIW, I think the standard library's unittest module is also a
code prion -- there's no other explanation for its thriving
despite competition from the vastly superior syntax of py.test
or nose.


More information about the Python-list mailing list