Construction getattr(obj, 'attr1.attr2', None)
does not work.
What are the best practices to replace this construction?
Divide that into two getattr statements?
getattr() is one of the coolest built-in functions in Python. It takes three arguments: an object. name of the object's attribute but in the string format.
The getattr() function returns the value of the specified attribute from the specified object.
The getattr approach is slower than the if approach, reducing an insignificant ~3% the performance if bar is set and a considerable~35% if is not set.
Python setattr() and getattr() goes hand-in-hand. As we have already seen what getattr() does; The setattr() function is used to assign a new value to an object/instance attribute.
You can use operator.attrgetter()
in order to get multiple attributes at once:
from operator import attrgetter
my_attrs = attrgetter(attr1, attr2)(obj)
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