
Since Tenacity’s official website only offers a straightforward API document, let’s start with the library’s installation and a few basic usage.
Installation
For those who’re using pip, simply run the next:
python -m pip install tenacity
For those who’re using Anaconda, Tenacity shouldn’t be within the default channel, so you could install it from conda-forge
:
conda install -c conda-forge tenacity
Basic usage
After installing Tenacity, let’s take a look at some basic usage of the library.
Simply add an @retry
decorator and your code may have retry capabilities:
@retry()
async def coro_func():
pass
For those who want your code to stop retrying after a certain variety of attempts, you may write it like this:
@retry(stop=stop_after_attempt(5))
async def coro_func():
pass
After all, to avoid frequent retries that will exhaust connection pools, I like to recommend adding a waiting time before each retry. For instance, if you ought to wait for two seconds before each connection:
@retry(wait=wait_fixed(2))
async def coro_func():
pass
Even though it’s not mentioned within the documentation, I prefer to attend an additional second longer than the last time before each retry to attenuate resource waste:
@retry(wait=wait_incrementing(start=1, increment=1, max=5))
async def coro_func():
pass
Finally, if the retry is attributable to an exception
being thrown in the tactic, it’s best to throw the exception
back out. This permits for more flexible exception handling when calling the tactic:
@retry(reraise=True, stop=stop_after_attempt(3))
async def coro_func():
pass