pythonpython-3.xgetattr

Get nested attribute from a python object


I have an object with nested attributes like so:

obj:
    attr_1:
        attr_2

When both attr_1 and attr_2 exists, I can get it like so:

obj.attr_1.attr_2

But what if I'm not sure if either attribute exists? In this case, construction of getattr(obj, 'attr_1.attr_2', None) does not work.

What are the best practices to replace this construction?

Divide that into two getattr statements?


Solution

  • You can use operator.attrgetter() in order to get multiple attributes at once:

    from operator import attrgetter
    
    my_attrs = attrgetter(attr1, attr2)(obj)