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

Steven D'Aprano steve at pearwood.info
Fri Apr 12 01:48:57 CEST 2013


On 12/04/13 08:24, 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')
>
> The `sorted` function can check whether the `key` argument is a string, and
> if so do an attribute lookup.

Why an attribute lookup? Why not a key lookup?

Using a trivial lambda makes it obvious what you want:

key=lambda obj: obj.name
key=lambda obj: obj[name]

and is more convenient (although probably slower) than the alternatives:

key=operator.attrgetter(name)
key=operator.itemgetter(name)


without ambiguity or guessing what the caller intended. It also avoids masking
TypeError errors if you call with a non-literal argument that happens to be a
string.

If we allow sorted etc. to guess what the caller wants with strings, should it
also guess what they want with integers?

key=3 equivalent to key=lambda obj: obj[3]

Hmmm... tempting... that would make sorting tuples by a specific field really
easy, which is an extremely common use case, and unlike strings, there's no
ambiguity.


So... -1 on allowing key='string' shortcuts, +0 on allowing key=3 shortcuts.



-- 
Steven



More information about the Python-ideas mailing list