Tenacity

https://tenacity.readthedocs.io/

CLEPY - February Module of the Month

David Thomas

dev@synth3.tk

What is Tenacity?

  • A "general-purpose retrying library", forked from... retrying
  • Extremely configurable
  • Not a city for people with tentacles

Features - Sell It To Me

  • It's a decorator! (boogie-woogie woogie)
  • Set your own stop condition (i.e. by number of attempts)
  • Specify wait condition
  • Combine conditions together!
  • Customize retrying on Exceptions or expected result
  • Has support for callbacks (ring ring, hello?)

Installation

pip install tenacity

Examples

- Basic Retry


In [ ]:
import random
from tenacity import retry

@retry
def do_something_unreliable():
    # Pick a number between 0 and 10
    if random.randint(0, 10) > 1:
        # If it's greater than 1, raise an error
        print("this number was bad...")
        raise Exception
    else:
        print("...but this one is good! :D")
        return

do_something_unreliable()

- Stop After (X) Attempts

- Reraise Exceptions


In [ ]:
from tenacity import retry, stop_after_attempt

@retry(reraise=True, stop=stop_after_attempt(3))
def raise_my_exception():
    print("Pass me the ball!")
    raise Exception()

try:
    raise_my_exception()
except Exception:
    # Ran out of attempts
    print("Whoa, time out, y'all...")
    pass

- Wait Between Attempts


In [ ]:
from tenacity import retry, wait_fixed

@retry(wait=wait_fixed(3))
def wait_3_s():
    print("Wait 3 seconds between retries")
    raise Exception
    
wait_3_s()

fin.