getting dynamic attribute in python [duplicate]
Asked Answered
H

5

33

I have and object with an pseudo or special attribute that can be named in three different ways (Note: I don't control the code which generates the object)

The value in the attributes (depending which one is set) is exactly the same, and I need to get that for further processing, so depending of the source of data, I can have something like:

>>> obj.a
'value'
>>> obj.b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: Obj instance has no attribute 'b'
>>> obj.c
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: Obj instance has no attribute 'c'

or

>>> obj.a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: Obj instance has no attribute 'a'
>>> obj.b
'value'
>>> obj.c
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: Obj instance has no attribute 'c'

or

>>> obj.a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: Obj instance has no attribute 'a'
>>> obj.b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: Obj instance has no attribute 'b'
 >>> obj.c
'value'

I'm interested in getting 'value' and unfortunately __dict__ property does not exist in that object. So what I ended doing for getting that value was just do a bunch of getattr calls. Assuming that possibilities are only three, the code looked like this:

>>> g = lambda o, l: getattr(o, l[0], getattr(o, l[1], getattr(o, l[2], None)))
>>> g(obj, ('a', 'b', 'c'))
'value'

Now, I would like to know whether there is a better way to this? As I'm 100% convinced what I've done :)

Thanks in advance

Hepatic answered 28/11, 2012 at 0:23 Comment(1)
Just to check - there isn't a get_value() (or similar) or as you mention depending of the source of data - no existing (or derivable mapping) of source -> attribute name?Geer
G
65

How about:

for name in 'a', 'b', 'c':
    try:
        thing = getattr(obj, name)
    except AttributeError:
        pass
    else:
        break
Gagman answered 28/11, 2012 at 0:30 Comment(5)
I was actually trying to avoid a try/except in this one ..I should've mentioned that :)Hepatic
try/except is the typical pythonic way, any good reason you wanted to avoid it?Gagman
Not any really good reason, just wanted to keep the code concise and I felt a try/except was a bit too much :) The other thing I was checking now is that the block does not provide a default value in case of none of these properties exist, although that is highly improbable, still I think it is always good to use a defensive approach :)Hepatic
You can do that using an else statement to the for loop, if that's what you need. As for style matters, the presence of many try/excepts is usual in python - see EAFPGagman
I didn't know about using else with for loops :) thanks for thatHepatic
P
3

This has the advantage of working with any number of items:

 def getfirstattr(obj, *attrs):
     return next((getattr(obj, attr) for attr in attrs 
                  if hasattr(obj, attr)), None)

This does have the very minor drawback that it does two lookups on the final value: once to check that the attribute exists, another to actually get the value. This can be avoided by using a nested generator expression:

 def getfirstattr(obj, *attrs):
     return next((val for val in (getattr(obj, attr, None) for attr in attrs)
                  if val is not None), None)

But I don't really feel it's a big deal. The generator expression is probably going to be faster than a plain old loop even with the double-lookup.

Perdomo answered 28/11, 2012 at 0:32 Comment(3)
I almost posted something to this effect. the problem is that you end up checking twice for the element you want (once with hasattr and once with getattr). Ultimately, I decided it wasn't really better than the explicit loop posted by wim -- Although I'm open to hearing about any advantages this might have over the loop.Lynnalynne
You could use a nested generator to avoid the double-lookup, I guess, but it only happens when it finds the attribute, so I consider it a minor drawback. I just added such a version, however.Perdomo
nice one...I'm going to have a look..thanksHepatic
L
1

I think using dir will get u essentially the same thing __dict__ normally does ...

targetValue = "value"
for k in dir(obj):
    if getattr(obj,k) == targetValue:
       print "%s=%s"%(k,targetValue)

something like

>>> class x:
...    a = "value"
...
>>> dir(x)
['__doc__', '__module__', 'a']
>>> X = x()
>>> dir(X)
['__doc__', '__module__', 'a']
>>> for k in dir(X):
...     if getattr(X,k) == "value":
...        print "%s=%s"%(k,getattr(X,k))
...
a=value
>>>
Lorna answered 28/11, 2012 at 0:27 Comment(1)
Thanks for this one, I completely missed dir()...just wondering now...how dir() call works internally. I'll checkHepatic
S
0

There may be a better way to do this depending on the structure of your object, but knowing nothing else, here is a recursive solution that works exactly like your current solution except that it will work with an arbitrary number of arguments:

g = lambda o, l: getattr(o, l[0], g(o, l[1:])) if l else None
Subsocial answered 28/11, 2012 at 0:32 Comment(1)
I really liked this one, for the simplicity and the brevityHepatic
L
-1

And another one:

reduce(lambda x, y:x or  getattr(obj, y, None),  "a b c".split(), None)

(in Python 3 you have to import reduce from functools. It is a builtin in Python 2)

Lankford answered 28/11, 2012 at 0:45 Comment(1)
This assumes that bool(obj.b) is True. Consider what would happen here if you had obj.a = 0. I don't think you would pick that up.Lynnalynne

© 2022 - 2024 — McMap. All rights reserved.