chained attrgetter

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
>>> from operator import add
>>> funcs = [lambda x:add('ANSWER: ', str(x)), lambda x:add(x,100)]
>>> compose(funcs)(9)
'ANSWER: 109'

"""
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]])
 
A

Alexey Borzenkov

Does something like operator.getattr exist to perform a chained attr
lookup?

Do you mean something like

class cattrgetter:
def __init__(self, name):
self.names = name.split('.')
def __call__(self, obj):
for name in self.names:
obj = getattr(obj, name)
return obj

?
 
B

Brian Beck

Alexey said:
Do you mean something like

class cattrgetter:
def __init__(self, name):
self.names = name.split('.')
def __call__(self, obj):
for name in self.names:
obj = getattr(obj, name)
return obj

I'll raise you one:

def cattrgetter(attr):
return lambda obj: reduce(getattr, attr.split('.'), obj)

py> class A: pass
py> a = A
py> a.b = A
py> a.b.c = "Hey!"
py> cattrgetter('b.c')(a)
'Hey!'
 
B

Brian Beck

David said:
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.

You were on the right track, but the built-in getattr is a perfectly
good argument to reduce(), using operator.attrgetter just makes the
definition more complicated (see my other post).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top