Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 991
gmoss Avatar asked Oct 18 '25 19:10

gmoss


1 Answers

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')))
like image 114
gmoss Avatar answered Oct 20 '25 08:10

gmoss