Skip to content

Instantly share code, notes, and snippets.

@Simsso
Created May 14, 2024 22:47
Show Gist options
  • Select an option

  • Save Simsso/38b1fe7a0c3a4b613094af74fed880ca to your computer and use it in GitHub Desktop.

Select an option

Save Simsso/38b1fe7a0c3a4b613094af74fed880ca to your computer and use it in GitHub Desktop.
Retry annotation for Python
import functools
import time
def retry(max_retries=3, delay_s=2):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
retries = max_retries
while retries > 0:
try:
return func(*args, **kwargs)
except Exception as e:
retries -= 1
print(f"Retry {max_retries - retries}/{max_retries}, Error: {e}")
if retries > 0:
time.sleep(delay_s)
else:
raise
return wrapper
return decorator
@Simsso
Copy link
Author

Simsso commented May 15, 2024

Example use:

@retry()
def function_which_is_unreliable():
  pass

important_output = function_which_is_unreliable()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment