[Python-ideas] list.sort with a int or str key
raymond.hettinger at gmail.com
Thu Sep 16 20:28:32 CEST 2010
On Sep 16, 2010, at 8:35 AM, Daniel Stutzbach wrote:
> list.sort, sorted, and similar methods currently have a "key" argument that accepts a callable. Often, that leads to code looking like this:
> mylist.sort(key=lambda x: x)
> myotherlist.sort(key=lambda x: x.length)
> I would like to propose that the "key" parameter be generalized to accept str and int types, so the above code could be rewritten as follows:
The key= parameter is a protocol that is used across multiple tools min(). max(), groupby(), nmallest(), nlargest(), etc. All of those would need to change to stay in-sync.
> I find the latter to be much more readable.
It also becomes harder to learn.
Multiple signatures (int or str or other callable) create more problems that they solve.
> As a bonus, performance for those cases would also improve.
ISTM, the performance would be about the same as you already get from attrgetter(), itemgetter(), and methodcaller(). Also, those three tools are already more flexible than the proposal, for example:
attrgetter('lastname', 'firstname') # key = lambda r: (r.lastname, r.firstname)
itemgetter(0, 7) # key = lambda r: (r, r)
methodcaller('get_stats', 'size') # key = lambda r: r.get_stats('size')
We've already got a way to do it, so the proposal is basically about saving a few characters in exchange for complexifying the protocol with a form of multiple dispatch.
More information about the Python-ideas