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

SilentGhost
  • 287,765
  • 61
  • 300
  • 288
Hellnar
  • 57,479
  • 74
  • 196
  • 273

2 Answers2

30

you could also use:

from operator import attrgetter
attrgetter('x.y.z')(doc)
SilentGhost
  • 287,765
  • 61
  • 300
  • 288
13

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

from functools import reduce
reduce(getattr, "X.Y.Z".split('.'), doc)
Community
  • 1
  • 1
kennytm
  • 491,404
  • 99
  • 1,053
  • 989