getting dynamic attribute in python

rhormaza picture rhormaza · Nov 28, 2012 · Viewed 22.7k times · Source

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

Answer

wim picture wim · Nov 28, 2012

How about:

for name in 'a', 'b', 'c':
    try:
        thing = getattr(obj, name)
    except AttributeError:
        pass
    else:
        break