Python: How to get object attribute attribute with getattr?

How to rate

a = myobject.id.number

and return None if it is myobject equal None

with built-in getattr? Maybe getattr(myobject, "id.number", None)?

+5
source share
5 answers
getattr(getattr(myobject, "id", None), "number", None)

must work.

+3
source

This should scale well to any depth:

reduce(lambda obj, attr : getattr(obj, attr, None), ("id","num"), myobject)
+5
source

Here is a single line

a = myobject is not None and myobject.id.number or None

It does not check if id is None, but that was not part of the original question.

+1
source

A little bit over a general solution preserving all members:

if myobject and myobject.id and myobject.id.number:
    a = myobject.id.number
else:
    a = None
0
source
return myobject.id.number if myobject else None
0
source

All Articles