retry.py 751 B

1234567891011121314151617181920212223242526272829
  1. import time
  2. import functools
  3. # Partly copy-pasted from contrib/python/retry
  4. def retry_func(f, exceptions=Exception, tries=-1, delay=1, max_delay=None, backoff=1):
  5. _tries, _delay = tries, delay
  6. while _tries:
  7. try:
  8. return f()
  9. except exceptions as e:
  10. _tries -= 1
  11. if not _tries:
  12. raise
  13. time.sleep(_delay)
  14. _delay *= backoff
  15. if max_delay is not None:
  16. _delay = min(_delay, max_delay)
  17. def retry(**retry_kwargs):
  18. def decorator(func):
  19. @functools.wraps(func)
  20. def wrapper(*args, **kwargs):
  21. return retry_func(lambda: func(*args, **kwargs), **retry_kwargs)
  22. return wrapper
  23. return decorator