Conquer Retries in Python Using Tenacity: An End-to-End Tutorial | by Peng Qian | Jul, 2023


Since Tenacity’s official website only offers a simple API document, let’s start with the library’s installation and some basic usage.

Installation

If you’re using pip, simply run the following:

python -m pip install tenacity

If you’re using Anaconda, Tenacity is not in the default channel, so you need to install it from conda-forge:

conda install -c conda-forge tenacity

Basic usage

After installing Tenacity, let’s look at some basic usage of the library.

Simply add an @retry decorator and your code will have retry capabilities:

@retry()
async def coro_func():
pass

If you want your code to stop retrying after a certain number of attempts, you can write it like this:

@retry(stop=stop_after_attempt(5))
async def coro_func():
pass

Of course, to avoid frequent retries that may exhaust connection pools, I recommend adding a waiting time before each retry. For example, if you want to wait for 2 seconds before each connection:

@retry(wait=wait_fixed(2))
async def coro_func():
pass

Although it’s not mentioned in the documentation, I prefer to wait an extra second longer than the last time before each retry to minimize resource waste:

@retry(wait=wait_incrementing(start=1, increment=1, max=5))
async def coro_func():
pass

Finally, if the retry is caused by an exception being thrown in the method, it is best to throw the exception back out. This allows for more flexible exception handling when calling the method:

@retry(reraise=True, stop=stop_after_attempt(3))
async def coro_func():
pass





Source link

Leave a Comment