[Python-ideas] Allow key='attribute_name' to various sorting functions

Oscar Benjamin oscar.j.benjamin at gmail.com
Fri Apr 12 01:05:38 CEST 2013


On 11 April 2013 23:52, Ram Rachum <ram.rachum at gmail.com> wrote:
> On Friday, April 12, 2013 1:35:20 AM UTC+3, Carl Meyer wrote:
>>
>> On 04/11/2013 04:24 PM, Ram Rachum wrote:
>> > I often want to sort objects by an attribute. It's cumbersome to do
>> > this:
>> >
>> >     sorted(entries, key=lambda entry: entry.datetime_created)
>> >
>> > Why not allow this instead:
>> >
>> >     sorted(entries, key='datetime_created')
>>
>>     from operator import attrgetter
>>     sorted(entries, key=attrgetter('datetime_created'))
>>
>> You can alias attrgetter to an even shorter name if you like.
>
> That's still cumbersome in my opinion.

I don't think it's that cumbersome. Leaving aside the import line
you're only having to specify two things for your key function: that
it's an attribute (attrgetter) and the name of the attribute
('datetime_created'). It's not possible for this to be any more
succinct without using special case implicit rules which are generally
a bad thing. I like the fact that the API for the sorted function is
so simple I can remember all of its arguments and exactly what they do
without ever needing to look it up.


Oscar



More information about the Python-ideas mailing list