Calmcode - stamina: explicit

Explicit Errors

1 2 3 4

This code will run just fine thanks to stamina.

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): 
    run(i)

But what if we change the error code inside of the function.

import random
import stamina

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

for i in range(10): 
    run(i)

This would totally break. That's because the error in the function no longer matches the error in the decorator.

Good practice

In general, it's a very good practice to be explicit about the errors that you want to catch. You only want to retry the situations that you understand very well and you typically want a program to fail if something unexpected happens. Then again, there are these rare occasions where you may want to catch everything, maybe early on when you're exploring something. For these moments you can also pass a general Exception.

import random
import stamina

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

for i in range(10): 
    run(i)

Know that you're able to have a "catch-all" if you really want. Just ... be careful when you do this. You typically don't want this.