in

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


Since Tenacity’s official website solely provides a easy API doc, let’s begin with the library’s set up and a few fundamental utilization.

Set up

If you happen to’re utilizing pip, merely run the next:

python -m pip set up tenacity

If you happen to’re utilizing Anaconda, Tenacity shouldn’t be within the default channel, so it’s essential set up it from conda-forge:

conda set up -c conda-forge tenacity

Primary utilization

After putting in Tenacity, let’s take a look at some fundamental utilization of the library.

Merely add an @retry decorator and your code can have retry capabilities:

@retry()
async def coro_func():
move

If you would like your code to cease retrying after a sure variety of makes an attempt, you may write it like this:

@retry(cease=stop_after_attempt(5))
async def coro_func():
move

In fact, to keep away from frequent retries that will exhaust connection swimming pools, I like to recommend including a ready time earlier than every retry. For instance, if you wish to wait for two seconds earlier than every connection:

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

Though it’s not talked about within the documentation, I choose to attend an additional second longer than the final time earlier than every retry to reduce useful resource waste:

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

Lastly, if the retry is brought on by an exception being thrown within the technique, it’s best to throw the exception again out. This enables for extra versatile exception dealing with when calling the strategy:

@retry(reraise=True, cease=stop_after_attempt(3))
async def coro_func():
move




Growing Scientific Software program. Half 2: Sensible Points with Python | by Carlos Costa, Ph.D. | Jul, 2023

Creating Scientific Software program. Half 1: Rules from Take a look at-Pushed… | by Carlos Costa, Ph.D. | Jul, 2023