Search code examples
pythonobjectgetattr

Python getattr() with another attribute as the default


I have two classes. One class has an attribute x but not y, and the other class has an attribute y but not x.

I have a function that accepts either class as an argument. Is there a one-line way to assign a new variable to the x attribute if it exists, or the y attribute if not? I.e.,

if hasattr(input_object, 'x'):
    new_var = input_object.x
else:
    new_var = input_object.y

I thought I would be able to do:

new_var = getattr(input_object, 'x', input_object.y)

But that raises an AttributeError if the input_object doesn't have y, even though it does have x.


Solution

  • Or you can use an if/else construct:

    new_var = (
      input_object.x if hasattr(input_object, 'x')
      else input_object.y
    )
    

    This will not evaluate input_object.y unless there is no input_object.x.