Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concise way to getattr() and use it if not None in Python

Tags:

python

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 
like image 970
Oliver Zheng Avatar asked Mar 11 '10 20:03

Oliver Zheng


People also ask

What is __ Getattr __?

__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).


1 Answers

Since you are calling the attr, you could just do:

def default_action():     # do something else  action = getattr(obj, 'attr', default_action)  action() 
like image 123
Joe Koberg Avatar answered Sep 25 '22 15:09

Joe Koberg