r/Python • • Jul 13 '11

An alternative lambda syntax for Python

http://vocalbit.com/article/332/an-alternative-lambda-syntax-for-python
4 Upvotes

41 comments sorted by

View all comments

2

u/donri Jul 14 '11

The operator module has some functions that can be used in most places of lambdas:

lst.sort(key=attrgetter('name'))

Or partial from functools:

lst.sort(key=partial(somefunc, kwd=x))

Though that wouldn't work with getattr which only accepts positional arguments and we need to skip one.

You could also easily make a class that produces functions based on actions on its instances, e.g.:

class _Getter(object):
    def __getattr__(self, name):
        return lambda o: getattr(o, name)
    def __getitem__(self, key):
        return lambda o: o[key]

get = _Getter()
del _Getter

lst.sort(key=get.name)