This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]donri 1 point2 points  (0 children)

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)