I am finding myself doing the following a bit too often:
attr = getattr(obj, 'attr', None) if attr is not None:     attr()     # Do something, either attr(), or func(attr), or whatever else:     # Do something else   Is there a more pythonic way of writing that? Is this better? (At least not in performance, IMO.)
try:     obj.attr() # or whatever except AttributeError:     # Do something else 
                __getattr__Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self).
Since you are calling the attr, you could just do:
def default_action():     # do something else  action = getattr(obj, 'attr', default_action)  action() 
                        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