[Python-ideas] Allow key='attribute_name' to various sorting functions
Carl Meyer
carl at oddbird.net
Fri Apr 12 00:35:20 CEST 2013
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.
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?
Carl
More information about the Python-ideas
mailing list