11
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
  • 307,395
  • 66
  • 306
  • 293
Hellnar
  • 62,315
  • 79
  • 204
  • 279

2 Answers2

35

you could also use:

from operator import attrgetter
attrgetter('x.y.z')(doc)
SilentGhost
  • 307,395
  • 66
  • 306
  • 293
15

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
  • 510,854
  • 105
  • 1,084
  • 1,005