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

Oscar Benjamin oscar.j.benjamin at gmail.com
Fri Apr 12 01:39:30 CEST 2013


On 12 April 2013 00:33, Haoyi Li <haoyi.sg at gmail.com> wrote:
> A more generic and useful thing would be kind of what scala/groovy have:
> shorthands for defining function literals:
>
> Groovy:
> myList.sort{it.startTime}
>
> Scala:
> myList.sort(_.startTime)
>
> Where "_.startTime" and "it.startTime" are shorthand for "x => x.startTime"
> or python's "lambda x: x.startTime". You could probably get something
> similar in python:
>
> sorted(entries, key = x.datetime_created)
>
> if you did some magic with x to make looking up an attribute return a lambda
> that returns that attribute of its argument.

You can do that if you want to:

import operator
class X(object):
    def __getattribute__(self, attrname):
        return operator.attrgetter(attrname)
    def __getitem__(self, index):
        return operator.itemgetter(index)
x = X()


Oscar



More information about the Python-ideas mailing list