[Python-ideas] list.sort with a int or str key
Antoine Pitrou
solipsis at pitrou.net
Thu Sep 16 18:11:29 CEST 2010
On Thu, 16 Sep 2010 10:35:14 -0500
Daniel Stutzbach
<daniel at stutzbachenterprises.com> 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[1])
> 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:
>
> mylist.sort(key=1)
> myotherlist.sort(key='length')
It is not obvious whether key='length' should use __getitem__ or
__getattr__. Your example claims attribute lookup but an indexed lookup
would be more consistent with key=1.
I'm quite skeptical towards this. Special cases make things harder to
remember, and foreign code more difficult to read.
Regards
Antoine.
More information about the Python-ideas
mailing list