https://tenacity.readthedocs.io/
- Basic Retry
In [ ]:
import random
from tenacity import retry
@retry
def do_something_unreliable():
# Pick a number between 0 and 10
if random.randint(0, 10) > 1:
# If it's greater than 1, raise an error
print("this number was bad...")
raise Exception
else:
print("...but this one is good! :D")
return
do_something_unreliable()
- Stop After (X) Attempts
- Reraise Exceptions
In [ ]:
from tenacity import retry, stop_after_attempt
@retry(reraise=True, stop=stop_after_attempt(3))
def raise_my_exception():
print("Pass me the ball!")
raise Exception()
try:
raise_my_exception()
except Exception:
# Ran out of attempts
print("Whoa, time out, y'all...")
pass
- Wait Between Attempts
In [ ]:
from tenacity import retry, wait_fixed
@retry(wait=wait_fixed(3))
def wait_3_s():
print("Wait 3 seconds between retries")
raise Exception
wait_3_s()