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


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

Set up

When you’re utilizing pip, merely run the next:

python -m pip set up tenacity

When you’re utilizing Anaconda, Tenacity just isn’t within the default channel, so you could set up it from conda-forge:

conda set up -c conda-forge tenacity

Fundamental utilization

After putting in Tenacity, let’s have a look at some primary 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’ll be able to write it like this:

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

In fact, to keep away from frequent retries which 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 attributable to an exception being thrown within the methodology, it’s best to throw the exception again out. This permits for extra versatile exception dealing with when calling the strategy:

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



Leave a Reply

Your email address will not be published. Required fields are marked *