-1

I check if an object has an attribute or another, can have only one.

If the attribute is found, assign his value to a variable. Can this be done dynamic(the attributes number can variate), getting from a list of possible attributes ?

if hasattr(o, 'a') or if hasattr(o, 'b') or if hasattr(o, 'c') or if hasattr(o, 'd'):

result = the one that exist
J Mo
  • 43
  • 6
  • `result = next((getattr(obj, attr) for attr in attributes if hasattr(obj, attr), None)`, here `attributes` is your list of attributes. If none are found, `result` will be `None` (you might want to use another value to signify an empty result). – Eli Korvigo Aug 15 '18 at 11:31
  • `break` is your friend: for attr in ['a', 'b', 'c', 'd']: if hasattr(o, attr): variable = attr break – leotrubach Aug 15 '18 at 11:34

1 Answers1

2

Make the attributes into a list and iterate through it:

for attr in ['a', 'b', 'c', 'd']:
    try:
        result = getattr(o, attr)
    except AttributeError:
        # Try the next one
        continue
    break
else:
    raise ValueError("No attribute found")

Apparently, the list can also be constructed dynamically.

iBug
  • 35,554
  • 7
  • 89
  • 134