Search code examples
pythonexceptionattributeshasattr

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?


Solution

  • 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.