Member-only story

Make your functions more tenace in Python

Kevin Tewouda
6 min readNov 22, 2023

--

Photo by Simone Pellegrini on Unsplash

There are many situations where we want to retry specific operations in case of errors. This is often the case in distributed systems (calling an external API, saving data in a remote data store, etc…). Here, I will present a nice Python library to do that.

Installation

The library is called tenacity. To install it, you will need Python 3.7 or higher.

$ pip install tenacity
# or with poetry
$ poetry add tenacity

If you don’t know poetry, I have a nice introduction to it here:

Usage

The simplest usage is to use the retry decorator it provides without parameters.

from tenacity import retry


@retry
def retry_without_limit():
print('retrying forever and ever!')
raise Exception


if __name__ == '__main__':
retry_without_limit()

Notes:

  • If you run the previous code, it will run indefinitely since there is no stop condition. 😜
  • In the next examples, I will omit the if

--

--

Kevin Tewouda
Kevin Tewouda

Written by Kevin Tewouda

Déserteur camerounais résidant désormais en France. Passionné de programmation, sport, de cinéma et mangas. J’écris en français et en anglais dû à mes origines.

Responses (2)