Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hasattr() vs try-except block to deal with non-existent attributes

if hasattr(obj, 'attribute'):     # do somthing 

vs

try:     # access obj.attribute except AttributeError, e:     # deal with AttributeError 

Which should be preferred and why?

like image 459
Imran Avatar asked May 24 '09 05:05

Imran


People also ask

Why use hasattr?

When attempting to access an attribute of a dynamic object, you can use hasattr() to avoid accessing errors. Chaining hasattr() is occasionally used to avoid entering one associated attribute if the other is not present.

Is hasattr fast?

hasattr() is not faster than getattr() since it goes through the exactly same lookup process and then throws away the result .

How do you check that obj1 has an attribute name?

We can use hasattr() function to find if a python object obj has a certain attribute or property. hasattr(obj, 'attribute'): The convention in python is that, if the property is likely to be there, simply call it and catch it with a try/except block.

How is Hasattr implemented?

hasattr() checks for the existence of an attribute by trying to retrieve it. This is implemented by calling getattr(object, name) , which does a lookup, and seeing whether an exception is raised.


2 Answers

Any benches that illustrate difference in performance?

timeit it's your friend

$ python -mtimeit -s 'class C(object): a = 4 c = C()' 'hasattr(c, "nonexistent")' 1000000 loops, best of 3: 1.87 usec per loop $ python -mtimeit -s 'class C(object): a = 4 c = C()' 'hasattr(c, "a")' 1000000 loops, best of 3: 0.446 usec per loop $ python -mtimeit -s 'class C(object): a = 4 c = C()' 'try:  c.a except:  pass' 1000000 loops, best of 3: 0.247 usec per loop $ python -mtimeit -s 'class C(object): a = 4 c = C()' 'try:  c.nonexistent except:  pass' 100000 loops, best of 3: 3.13 usec per loop $         |positive|negative hasattr|  0.446 |  1.87  try    |  0.247 |  3.13 
like image 156
ZeD Avatar answered Oct 09 '22 23:10

ZeD


hasattr internally and rapidly performs the same task as the try/except block: it's a very specific, optimized, one-task tool and thus should be preferred, when applicable, to the very general-purpose alternative.

like image 24
Alex Martelli Avatar answered Oct 09 '22 21:10

Alex Martelli