Member-only story

Use the Tenacity Library to Retry Functions in Python

Learn an elegant and robust way to retry functions or code blocks in Python

Lynn G. Kwong
5 min readNov 9, 2024
Image by geralt on Pixabay

Tenacity is an Apache 2.0 licensed general-purpose retrying library written in Python. It can retry on both sync and async functions. It can even retry on code blocks without a function. Last but not least, tenacity has very flexible settings and we can retry functions with custom stop, wait, and trigger conditions.

In this post, we will introduce how to use the tenacity library to retry functions or code blocks in an elegant and robust way in Python.

Install tenacity

To use tenacity in your project, you need to install it as a dependency with pip, uv or any dependency management tool.

pip install tenacity

# Or

uv add tenacity

Basic retry

First, let’s check the basic retry functionality of tenacity. Tenacity provides a decorator called retry which can be added to a function to retry it if it fails…

--

--

Lynn G. Kwong
Lynn G. Kwong

Written by Lynn G. Kwong

I’m a Software Developer (https://youtube.com/@kwonglynn) keen on sharing thoughts, tutorials, and solutions for the best practice of software development.

No responses yet