tags:

views:

55

answers:

2
import amara
def chain_attribute_call(obj, attlist):
    """
    Allows to execute chain attribute calls
    """
    splitted_attrs = attlist.split(".")
    current_dom = obj
    for attr in splitted_attrs:
        current_dom = getattr(current_dom, attr)
    return current_dom

doc = amara.parse("sample.xml")
print chain_attribute_call(doc, "X.Y.Z")

In oder to execute chain attribute calls for an object as a string, I had to develop the clumsy snippet above. I am curious if there would be a more clever / efficient solution to this.

+1  A: 

Just copying from Useful code which uses reduce() in Python:

from functools import reduce
reduce(getattr, "X.Y.Z".split('.'), doc)
KennyTM
Great snipplet! Sadly my server is debian lenny and runs with python 2.5 while reduce requires 2.6 :(
Hellnar
@hellinar: `reduce` is a built-in function in python2.5
SilentGhost
@Hellnar: Python 2.5 has `reduce`, except it is a built-in function instead of being in `functools`.
KennyTM
oh, thanks for the clarification!
Hellnar
BTW, `reduce` is still a built-in function in Python 2.6 and 2.7 (it would be horrible to remove built-in functions without changing the major version number). Only the 3.x series has it in the `functools` module exclusively.
Philipp
+1  A: 

you could also use:

from operator import attrgetter
attrgetter('x.y.z')(doc)
SilentGhost