if hasattr(obj, \'attribute\'):
# do somthing
vs
try:
# access obj.attribute
except AttributeError, e:
# deal with Attr
This subject was covered in the EuroPython 2016 talk Writing faster Python by Sebastian Witowski. Here's a reproduction of his slide with the performance summary. He also uses the terminology look before you leap in this discussion, worth mentioning here to tag that keyword.
If the attribute is actually missing then begging for forgiveness will be slower than asking for permissions. So as a rule of thumb you can use the ask for permission way if know that it is very likely that the attribute will be missing or other problems that you can predict. Otherwise if you expect code will result in most of the times readable code
# CASE 1 -- Attribute Exists
class Foo(object):
hello = 'world'
foo = Foo()
if hasatter(foo, 'hello'):
foo.hello
## 149ns ##
try:
foo.hello
except AttributeError:
pass
## 43.1 ns ##
## 3.5 times faster
# CASE 2 -- Attribute Absent
class Bar(object):
pass
bar = Bar()
if hasattr(bar, 'hello'):
bar.hello
## 428 ns ##
try:
bar.hello
except AttributeError :
pass
## 536 ns ##
## 25% slower