Everyday Utilities

tenacity

Teaches your code to shrug off a failure and just try again, instead of giving up immediately.

Install it: pip install tenacity

What does it do?

Tenacity wraps a risky piece of code, like a request to a website that might be temporarily down, in automatic retry logic, so instead of failing instantly on the first hiccup, it waits a moment and tries again, up to a number of attempts you choose. You can tell it to wait longer between each try, give up after a set number of attempts or a total time limit, and only retry certain kinds of failures rather than everything. It turns what would otherwise be a hand-rolled tangle of loops and error handling into a single decorator placed above a function. It’s a small addition that makes software noticeably more resilient to the flaky nature of networks and external services.

See it in action

This automatically retries a task that might temporarily fail, like a request to a website, up to three times with a short pause in between, instead of giving up immediately.

from tenacity import retry, stop_after_attempt, wait_fixed

@retry(stop=stop_after_attempt(3), wait=wait_fixed(2))
def call_flaky_service():
    print("Trying the request...")
    raise ConnectionError("temporary failure")

call_flaky_service()

Why would a non-developer care?

Nearly every app you use talks to other computers over the internet constantly, and the internet fails in small, temporary ways all the time. Software that quietly retries a failed request instead of immediately showing an error is a big reason apps feel dependable even though the internet underneath them isn’t.

Real-world examples

It’s widely used inside production backend systems that talk to databases, payment processors, or third-party APIs, precisely because those connections fail transiently often enough that retrying automatically saves real money and customer frustration. Cloud infrastructure tooling across the industry uses retry logic conceptually identical to what tenacity provides.

Who uses it

Backend developers building systems that depend on external services, databases, or networks that occasionally fail temporarily.

How it compares to alternatives

It’s the modern, actively maintained option for this exact job in Python; compared to writing retry loops by hand, its main competition is really developers who haven’t discovered it yet and are rolling their own less robust version.

New to Python and want to actually try libraries like this yourself?

Find a beginner-friendly course

Related libraries