Python Chain getattr as a string
Asked Answered
D

2

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.

Dg answered 19/7, 2010 at 7:16 Comment(0)
R
15

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

from functools import reduce
reduce(getattr, "X.Y.Z".split('.'), doc)
Raybourne answered 19/7, 2010 at 7:16 Comment(5)
Great snipplet! Sadly my server is debian lenny and runs with python 2.5 while reduce requires 2.6 :(Dg
@hellinar: reduce is a built-in function in python2.5Wardrobe
@Hellnar: Python 2.5 has reduce, except it is a built-in function instead of being in functools.Raybourne
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.Imperfective
Excellent solution!Karankaras
W
36

you could also use:

from operator import attrgetter
attrgetter('x.y.z')(doc)
Wardrobe answered 19/7, 2010 at 16:46 Comment(0)
R
15

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

from functools import reduce
reduce(getattr, "X.Y.Z".split('.'), doc)
Raybourne answered 19/7, 2010 at 7:16 Comment(5)
Great snipplet! Sadly my server is debian lenny and runs with python 2.5 while reduce requires 2.6 :(Dg
@hellinar: reduce is a built-in function in python2.5Wardrobe
@Hellnar: Python 2.5 has reduce, except it is a built-in function instead of being in functools.Raybourne
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.Imperfective
Excellent solution!Karankaras

© 2022 - 2024 — McMap. All rights reserved.