Calmcode - stamina: introduction

Retry with Stamina

1 2 3 4

Sometimes a Python function can fail because of something that is outside of your control. The most typical example of this is a failing request made to an external server. In these cases you don't want an entire program to fail, but you'd like to allow the program to wait for a moment before trying again.

Stamina is a great library for this. So let's first install it.

python -m pip install stamina

Once installed, you can run this quick demo snippet.

import random
import stamina

@stamina.retry(on=ValueError, attempts=7)
def run(i):
    if random.random() < 0.5:
        raise ValueError("oh no")
    return i

for i in range(10): 

Notice how this program will probably fail because the run function raises a ValueError half the time? When you run it doesn't break though, because this function is decorated with a retry decorator from stamina. This decorator will allow the function to retry a few times before finally giving up.

Stamina does a few things under the hood that are very sensible, so we'll dive into some more details as this course proceeds.