What is a decorator? Write a retry decorator.
IntermediateConceptLanguage essentials & functions
Answer
A decorator takes a function and returns a new function that wraps it.
import functools, logging, random, time
log = logging.getLogger(__name__)
def retry(times=5, base=0.5, exceptions=(ConnectionError,)):
def deco(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
for attempt in range(1, times + 1):
try:
return fn(*args, **kwargs)
except exceptions as exc:
if attempt == times:
raise
delay = base * 2 ** (attempt - 1) + random.uniform(0, base)
log.warning("%s failed (%s), retry %d in %.1fs", fn.__name__, exc, attempt, delay)
time.sleep(delay)
return wrapper
return deco
In production we usually reach for tenacity instead of hand-rolling this.
More on Language essentials & functions
Why is Python the default scripting language in so many DevOps teams, and where would you not use it?BeginnerWhat is the difference between mutable and immutable types? Give examples.BeginnerWhat does assignment do in Python, and how do shallow and deep copies differ?BeginnerExplain the mutable default argument bug and how to fix it.IntermediateWhat is the difference between `==` and `is`?BeginnerWhat values are "falsy" in Python, and why does it matter in scripts?Beginner