6/29/2018 - 4:56 AM

Task retry by Tenacity

Tenacity is an Apache 2.0 licensed general-purpose retrying library, written in Python, to simplify the task of adding retry behavior to just about anything. It originates from a fork of retrying.

The simplest use case is retrying a flaky function whenever an Exception occurs until a value is returned.

#github url:

import random
from tenacity import retry

def do_something_unreliable():
    if random.randint(0, 10) > 1:
        raise IOError("Broken sauce, everything is hosed!!!111one")
        return "Awesome sauce!"


#Othter example
#Let's be a little less persistent and set some boundaries, such as the number of attempts before giving up.
def stop_after_7_attempts():
    print("Stopping after 7 attempts")
    raise Exception
#We don't have all day, so let's set a boundary for how long we should be retrying stuff.
def stop_after_10_s():
    print("Stopping after 10 seconds")
    raise Exception
#You can combine several stop conditions by using the | operator
@retry(stop=(stop_after_delay(10) | stop_after_attempt(5)))
def stop_after_10_s_or_5_retries():
    print("Stopping after 10 seconds or 5 retries")
    raise Exception