Retries with Tenacity lib in Python

Prasad
2 min readJun 30, 2022

--

Tenacity is an Apache 2.0 licensed general-purpose retrying library, written in Python, to simplify the task of adding retry behavior to just about anything. It originates from a fork of Retrying

The simplest use case is retrying a flaky function whenever an Exception occurs until a value is returned.

If you are data engineer or Frontend developer ,then if a huge block of code for downloading or upload a file from a server always a problem.Retry package in python which longer not maintained .So i am looking out for another package which gives a flexibility in retrying.Finally found Tenacity which provides some flexibility in handling retry.

Here what Tenacity Provides -

pip install tenacity
import random
from tenacity import retry,stop_after_attempt
@retry
def do_something_unreliable():
if random.randint(0, 10) > 1: raise IOError("Broken sauce, everything is hosed!!!111one") else: return "Awesome sauce!"
print(do_something_unreliable())
@retry
def never_give_up_never_surrender():
print("Retry forever ignoring Exceptions, don't wait between retries") raise Exception('tenacity try...')
output
@retry(stop=stop_after_attempt(7))def stop_after_7_attempts():
print("Stopping after 7 attempts")
raise Exception('tenacity try...'
stop_after_7_attempts()
retry for 7 times

--

--

Prasad
Prasad

Written by Prasad

I am a OpenSource Enthusiast|Python Lover who attempts to find simple explanations for questions and share them with others

No responses yet