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
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…