hasattr() ,try-except block and getattr()

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:
  1. getattr does not have the bad exception-swallowing behavior pointed out by Martin Geiser - in old Pythons, hasattr will even swallow a KeyboardInterrupt.
  2. 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.
  3. 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.)
  4. It's shorter than try/finally and often shorter than hasattr.
  5. A broad except AttributeError block can catch other AttributeErrors than the one you're expecting, which can lead to confusing behaviour.
  6. 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