if hasattr(obj, 'attribute'):
# do somthing
vs
try:
# access obj.attribute
except AttributeError, e:
# deal with AttributeError
Which should be preferred and why?
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.