Search code examples
pythonclosurescython

pythonic way of composing itemgetter and attrgetter?


I've got some code I'm porting to Cython which had a line like

my_list.sort(key=lambda x: x.attr[item])

Is there a nice pythonic way of avoiding the closure with some combination of itemgetter and attrgetter?


Solution

  • The key is to use the package functional:

    from functional import compose
    from operator import attrgetter, itemgetter
    my_list.sort(key=compose(itemgetter(item), attrgetter('attr')))