[Python-ideas] Allow key='attribute_name' to various sorting functions
Ram Rachum
ram.rachum at gmail.com
Fri Apr 12 00:52:57 CEST 2013
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.
>
> Explicit utility functions are better than implicit special-case
> behaviors. Why should a string be special-cased to attribute lookup
rather than, say, __getitem__ lookup?
>
Right, these are options too. I'd guess that attribute lookup is more
common, but maybe I'm wrong.
>
> Carl
> _______________________________________________
> Python-ideas mailing list
> Python... at python.org <javascript:>
> http://mail.python.org/mailman/listinfo/python-ideas
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130411/7a49cef1/attachment.html>
More information about the Python-ideas
mailing list