Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Chain getattr as a string

Tags:

python

getattr

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.

like image 373
Hellnar Avatar asked Jul 19 '10 07:07

Hellnar


1 Answers

you could also use:

from operator import attrgetter
attrgetter('x.y.z')(doc)
like image 51
SilentGhost Avatar answered Sep 23 '22 09:09

SilentGhost