12
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.

2 Answers 2

36

you could also use:

from operator import attrgetter
attrgetter('x.y.z')(doc)
Sign up to request clarification or add additional context in comments.

Comments

15

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

from functools import reduce
reduce(getattr, "X.Y.Z".split('.'), doc)

5 Comments

Great snipplet! Sadly my server is debian lenny and runs with python 2.5 while reduce requires 2.6 :(
@hellinar: reduce is a built-in function in python2.5
@Hellnar: Python 2.5 has reduce, except it is a built-in function instead of being in functools.
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.
Excellent solution!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.