Deina Underhill
Deina Underhill

Reputation: 567

How to point to value of variable

To avoid writing a long, ugly ternary a dozen times, such as p_count = root.pool_count if hasattr(root, 'pool_count') else (-1), I wrote the GetThis(el, attr, err="") function.

How do I get the function to concatenate the values of el & attr into an element, instead of attr as a literal?

test_data = ("""
    <rsp stat="ok">
        <group id="34427465497@N01" iconserver="1" iconfarm="1" lang="" ispoolmoderated="0" is_member="0" is_moderator="0" is_admin="0">
            <name>GNEverybody</name>
            <members>245</members>
            <pool_count>133</pool_count>
            <topic_count>106</topic_count>
            <restrictions photos_ok="1" videos_ok="1" images_ok="1" screens_ok="1" art_ok="1" safe_ok="1" moderate_ok="0" restricted_ok="0" has_geo="0" />
        </group>
    </rsp>
""")
    ################

from lxml import etree
from lxml import objectify
    ################

def GetThis(el, attr, err=""):
    if hasattr(el, attr):
        return el.attr
    else:
        return err
    ################

Grp = objectify.fromstring(test_data)
root = Grp.group

gName   = GetThis(root, "name", "No Name")
err_tst = GetThis(root, "not-there", "Error OK")
p_count = root.pool_count if hasattr(root, 'pool_count') else (-1)

As it is, I get the following error:

Traceback (most recent call last):
    File "C:/Mirc/Python/Temp Files/test_lxml.py", line 108, in <module>
        gName  = GetThis(root, "name", "")
    File "C:/Mirc/Python/Temp Files/test_lxml.py", line 10, in GetThis
        print (el.attr)
    File "lxml.objectify.pyx", line 218, in lxml.objectify.ObjectifiedElement.__getattr__ (src\lxml\lxml.objectify.c:3506)
    File "lxml.objectify.pyx", line 437, in lxml.objectify._lookupChildOrRaise (src\lxml\lxml.objectify.c:5756)
AttributeError: no such child: attr

Thank you!

Upvotes: 1

Views: 252

Answers (2)

Hacketo
Hacketo

Reputation: 4997

Python has a function called getattr(foo,"bar") which return the value of the bar attr of the foo object. Just read the doc ..

Upvotes: 0

user2555451
user2555451

Reputation:

Your GetThis function is not needed since you can simply use getattr:

gName   = getattr(root, "name", "No Name")
err_tst = getattr(root, "not-there", "Error OK")

The first argument is the object, the second is the attribute, and the third, which is optional, is a default value to return if the attribute doesn't exist (if this last part is omitted, an AttributeError is raised instead).

The two lines of code above are equivalent to these:

gName   = root.name if hasattr(root, "name") else "No Name"
err_tst = root.not-there if hasattr(root, "not-there") else "Error OK"

Upvotes: 6

Related Questions