2 min read

Python Tenacity Module

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.

Installation

pip install tenacity

Basic Usage

The simplest use case is to retry a function forever until it succeeds.

from tenacity import retry

@retry
def do_something_unreliable():
    if random.randint(0, 10) > 1:
        raise IOError("Broken sauce, everything is broken")
    else:
        return "Awesome sauce!"

print(do_something_unreliable())

Stopping Strategies

You can configure when to stop retrying.

from tenacity import retry, stop_after_attempt, stop_after_delay

# Stop after 7 attempts
@retry(stop=stop_after_attempt(7))
def stop_after_7_attempts():
    print("Stopping after 7 attempts")
    raise Exception

# Stop after 10 seconds
@retry(stop=stop_after_delay(10))
def stop_after_10_s():
    print("Stopping after 10 seconds")
    raise Exception

Waiting Strategies

You can configure how long to wait between retries.

from tenacity import retry, wait_fixed, wait_exponential

# Wait 2 seconds between retries
@retry(wait=wait_fixed(2))
def wait_2_s():
    print("Wait 2s")
    raise Exception

# Wait 2^x * 1 second between each retry starting with 4 seconds, then up to 10 seconds, then 10 seconds afterwards
@retry(wait=wait_exponential(multiplier=1, min=4, max=10))
def wait_exponential_1():
    print("Wait exponential")
    raise Exception

Retry on Specific Exceptions

You can configure which exceptions trigger a retry.

from tenacity import retry, retry_if_exception_type

@retry(retry=retry_if_exception_type(IOError))
def might_io_error():
    print("Retry forever with no wait if an IOError occurs, raise any other exception")
    raise IOError

programming/python/python