context_managers.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. from __future__ import unicode_literals
  2. from timeit import default_timer
  3. from .decorator import decorate
  4. class ExceptionCounter(object):
  5. def __init__(self, counter, exception):
  6. self._counter = counter
  7. self._exception = exception
  8. def __enter__(self):
  9. pass
  10. def __exit__(self, typ, value, traceback):
  11. if isinstance(value, self._exception):
  12. self._counter.inc()
  13. def __call__(self, f):
  14. def wrapped(func, *args, **kwargs):
  15. with self:
  16. return func(*args, **kwargs)
  17. return decorate(f, wrapped)
  18. class InprogressTracker(object):
  19. def __init__(self, gauge):
  20. self._gauge = gauge
  21. def __enter__(self):
  22. self._gauge.inc()
  23. def __exit__(self, typ, value, traceback):
  24. self._gauge.dec()
  25. def __call__(self, f):
  26. def wrapped(func, *args, **kwargs):
  27. with self:
  28. return func(*args, **kwargs)
  29. return decorate(f, wrapped)
  30. class Timer(object):
  31. def __init__(self, callback):
  32. self._callback = callback
  33. def _new_timer(self):
  34. return self.__class__(self._callback)
  35. def __enter__(self):
  36. self._start = default_timer()
  37. def __exit__(self, typ, value, traceback):
  38. # Time can go backwards.
  39. duration = max(default_timer() - self._start, 0)
  40. self._callback(duration)
  41. def __call__(self, f):
  42. def wrapped(func, *args, **kwargs):
  43. # Obtaining new instance of timer every time
  44. # ensures thread safety and reentrancy.
  45. with self._new_timer():
  46. return func(*args, **kwargs)
  47. return decorate(f, wrapped)