D
David S.
Does something like operator.getattr exist to perform a chained attr
lookup?
I came up with the following, but I can not help but think it is
already done and done better.
Peace,
David S.
def compose(funcs):
""" return composite of funcs
this does not support extended call syntax, so each func can
only take a single arg
"""
def _func(arg):
return reduce(lambda v,f: f(v), iter(funcs[::-1]), arg)
return _func
def chained_attrgetter(cattr):
""" 'Hey, now!'
"""
return compose([attrgetter(attr) for attr in
cattr.split('.')[::-1]])
lookup?
I came up with the following, but I can not help but think it is
already done and done better.
Peace,
David S.
def compose(funcs):
""" return composite of funcs
this does not support extended call syntax, so each func can
only take a single arg
'ANSWER: 109'>>> from operator import add
>>> funcs = [lambda x:add('ANSWER: ', str(x)), lambda x:add(x,100)]
>>> compose(funcs)(9)
"""
def _func(arg):
return reduce(lambda v,f: f(v), iter(funcs[::-1]), arg)
return _func
def chained_attrgetter(cattr):
""" 'Hey, now!'
"""
return compose([attrgetter(attr) for attr in
cattr.split('.')[::-1]])