Don't like ads? PRO users don't see any ads ;-)
Guest

try/except vs getattr

By: a guest on Aug 1st, 2012  |  syntax: Python  |  size: 0.94 KB  |  hits: 23  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. >>> timer_try_except = Timer(
  2. ...     """
  3. ...     item = object()
  4. ...     try:
  5. ...         something = item.landlord.id
  6. ...     except AttributeError:
  7. ...         pass
  8. ...     """
  9. ... )
  10. >>>
  11. >>> timer_getattr = Timer(
  12. ...     """
  13. ...     item = object()
  14. ...     def try_getattr():
  15. ...         landlord = getattr(item, 'landlord', None)
  16. ...         if landlord:
  17. ...             pass #normally do something here
  18. ...     """
  19. ... )
  20. >>> iterations = 9999999
  21. >>> try_except_duration = timer_try_except.timeit(iterations)
  22. >>> getattr_duration = timer_getattr.timeit(iterations)
  23. >>> print 'try/except Duration: %f, %% of getattr: %f%%' % (try_except_duration, (try_except_duration / getattr_duration) * 100)
  24. try/except Duration: 11.601219, % of getattr: 606.159781%
  25. >>> print 'getattr Duration: %f, %% of try/except: %f%%' % (getattr_duration, (getattr_duration / try_except_duration) * 100)
  26. getattr Duration: 1.913888, % of try/except: 16.497300%