chained attrgetter

David S. davidschein at alumni.tufts.edu
Wed Oct 25 14:00:22 EDT 2006


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):
    """
    >>> class A: pass
    ...
    >>> a1 = A
    >>> a1.a2 = A
    >>> a1.a2.a3 = "Hey, now!"
    >>> chained_attrgetter("a2.a3")(a1)
    'Hey, now!'

    """
    return compose([attrgetter(attr) for attr in
cattr.split('.')[::-1]])




More information about the Python-list mailing list