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?
-1 on both :-)
Regards
Antoine.
Le Fri, 12 Apr 2013 09:48:57 +1000,
Steven D'Aprano <st...@pearwood.info> a
écrit :
> So... -1 on allowing key='string' shortcuts, +0 on allowing key=3-1 on both :-)
> shortcuts.
>------------------------------------------------------------------------
>
>_______________________________________________
>Python-ideas mailing list
>Python...@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)