[Python-ideas] Allow key='attribute_name' to various sorting functions
Markus Unterwaditzer
markus at unterwaditzer.net
Fri Apr 12 20:28:20 CEST 2013
Ram Rachum <ram.rachum at gmail.com> wrote:
>That would work for me, +1. (Though I imagine this idea will be
>showered
>with -1 from ebd...)
>
>
>On Fri, Apr 12, 2013 at 9:19 PM, Markus Unterwaditzer <
>markus at unterwaditzer.net> wrote:
>
>> Ram Rachum <ram.rachum at gmail.com> 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')
>> >
>> >The `sorted` function can check whether the `key` argument is a
>string,
>> >and
>> >if so do an attribute lookup.
>> >
>> >Since I see no other possible use of a string input to `key`, I
>don't
>> >see
>> >how this feature would harm anyone.
>> >
>> >What do you think?
>> >
>> >
>> >Thanks,
>> >Ram.
>> >
>> >
>>
>>------------------------------------------------------------------------
>> >
>> >_______________________________________________
>> >Python-ideas mailing list
>> >Python-ideas at python.org
>> >http://mail.python.org/mailman/listinfo/python-ideas
>>
>> I think it's a very bad idea to try to overload the key argument, imo
>a
>> separate kwarg of sorted would be fine though. E.g:
>>
>> sorted(iterable, attribute='someattr')
>>
>> -- Markus (from phone)
>>
Although i think it's better to use attrgetter, since it is more easily reusable and so on.
-- Markus (from phone)
More information about the Python-ideas
mailing list