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. Advantages:
getattr
does not have the bad exception-swallowing behavior pointed out by Martin Geiser - in old Pythons,hasattr
will even swallow aKeyboardInterrupt
.- The normal reason you're checking if the object has an attribute is so that you can use the attribute, and this naturally leads in to it.
- The attribute is read off atomically, and is safe from other threads changing the object. (Though, if this is a major concern you might want to consider locking the object before accessing it.)
- It's shorter than
try/finally
and often shorter thanhasattr
. - A broad
except AttributeError
block can catch otherAttributeErrors
than the one you're expecting, which can lead to confusing behaviour. - Accessing an attribute is slower than accessing a local variable (especially if it's not a plain instance attribute). (Though, to be honest, micro-optimization in Python is often a fool's errand.)
ex:
attr = getattr(obj, 'attribute', None)
if attr is not None:
print attr
No comments:
Post a Comment