Using tenacity (Python module): Retrying code block without def

Viewed 12

From https://tenacity.readthedocs.io/en/latest/#retrying-code-block

"Tenacity allows you to retry a code block without the need to wraps it in an isolated function. This makes it easy to isolate failing block while sharing context. The trick is to combine a for loop and a context manager."

from tenacity import Retrying, RetryError, stop_after_attempt

try:
    for attempt in Retrying(stop=stop_after_attempt(3)):
        with attempt:
            raise Exception('My code is failing!')
except RetryError:
    pass

I don't understand how a for loop is relevant here and how this is supposed to work.

  1. Is Retrying(stop=stop_after_attempt(3)) supposed to be a list here? If so, what does that list look like?
  2. with attempt: what does this mean?
  3. what is RetryError supposed to be?

I'm interested in applying a retry to any given block of code: @retry(wait=wait_fixed(2), stop=stop_after_attempt(5)) but it seems like this can only be placed before a def. How would I apply this retry to a block of code:

@retry(wait=wait_fixed(2), stop=stop_after_attempt(5)):
    # a block of code

Yes, I know the immediately above is not valid syntax, but it illustrates the desired effect.

0 Answers
Related