I very often write code like:
sorted(some_dict.items(), key=lambda x: x[1])
sorted(list_of_dicts, key=lambda x: x['age'])
map(lambda x: x.name, rows)
where I would like to write:
sorted(some_dict.items(), key=idx_f(1))
sorted(list_of_dicts, key=idx_f('name'))
map(attr_f('name'), rows)
using:
def attr_f(field):
return lambda x: getattr(x, field)
def idx_f(field):
return lambda x: x[field]
Are there functor-creators like idx_f and attr_f in python, and are they of clearer when used than lambda's?
The
operator
module hasoperator.attrgetter()
andoperator.itemgetter()
that do just that:These functions also take more than one argument, at which point they'll return a tuple containing the value for each argument:
The
attrgetter()
function also accepts dotted names, where you can reach attributes of attributes: