How do I evaluate
a = myobject.id.number
and return None if it myobject is None
with built-in getattr
? Maybe getattr(myobject, "id.number", None)
?
getattr(getattr(myobject, "id", None), "number", None)
should work.
This should scale well to any depth:
reduce(lambda obj, attr : getattr(obj, attr, None), ("id","num"), myobject)
my favorites are
from functools import reduce
try:
a = reduce(getattr, ("id", "number"), myobject)
except AttributeError:
a = None
or
from operator import attrgetter
try:
a = attrgetter('id.number')(myobject)
except AttributeError:
a = None
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With