if hasattr(obj, 'attribute'): # do somthing
vs
try: # access obj.attribute except AttributeError, e: # deal with AttributeError
Which should be preferred and why?
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.
hasattr() is not faster than getattr() since it goes through the exactly same lookup process and then throws away the result .
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.
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.
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
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.
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