A Retry Decorator
Write a decorator factory retry(times), used like this:
python
@retry(3)
def fetch():
...
The decorated function is called; if it raises an exception it is called again, up to times calls in total. The first successful result is returned. If every call fails, the last exception is raised. The decorated function keeps its name and accepts any arguments.
Understand the problem
Understand the three layers.
@retry(3) is the same as which pair of steps?
f = retry(f, 3)decorator = retry(3)thenf = decorator(f)f = retry(3)(3)
The expression after @ is evaluated first: retry(3) runs and must return a decorator. That decorator is then applied to the function. So retry returns a function that takes a function that returns a wrapper: three layers.
Which layer sees the argument times?
- Only the outermost,
retry(times), and the inner layers reach it through closure - The wrapper only
- None: it must be a global
The two inner functions are defined inside retry, so they can read times as a closed-over variable. No global is needed.
Write the solution
Write the three layers.
def retry(times):
# Write your code here.
pass
Hint 1: a question to ask yourself
What does retry(3) have to return so that the line @retry(3) works as an ordinary decorator?
Hint 2: the shape of the answer
def retry(times): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): ... return wrapper; return decorator. In the wrapper, loop times times with try: return func(...) and remember the last exception.
Reflect
Solution
import functools
def retry(times):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
last_error = None
for _ in range(times):
try:
return func(*args, **kwargs)
except Exception as error:
last_error = error
raise last_error
return wrapper
return decorator
What this tests: decorators with arguments (a function that returns a decorator), closures over times, functools.wraps, and exception handling.
Reading the layers: retry(3) is a plain call that returns decorator. decorator(func) is the usual decorator step and returns wrapper. wrapper(...) is the call at run time. When you are lost, write out f = retry(3)(f).
The forgotten-parentheses bug: @retry (without (3)) passes the function as times, and the first call of the function fails oddly. A decorator that works both with and without arguments is possible but needs extra code; most libraries choose one.
Reuse: the loop is the same as the call_with_retry function of the Errors chapter. A decorator is the same logic applied to every call automatically.
What an interviewer might ask next: Retry only on certain exceptions: @retry(3, on=ConnectionError). (Add a parameter and use except on as error.)
VISIBLE = 3
CASES = [
('calls = []\n@retry(3)\ndef flaky():\n calls.append(1)\n if len(calls) < 3:\n raise ConnectionError("down")\n return "ok"\nresult = (flaky(), len(calls))', ('ok', 3), 'succeeds on the third call'),
('calls = []\n@retry(2)\ndef bad():\n calls.append(1)\n raise KeyError("k")\nresult = (error_of(bad), len(calls))', ('KeyError', 2), 'always fails: 2 calls, then the error'),
('@retry(5)\ndef f(a, b=1):\n return a + b\nresult = f(1, b=2)', 3, 'arguments are passed on'),
('@retry(3)\ndef f():\n """Doc."""\nresult = (f.__name__, f.__doc__)', ('f', 'Doc.'), 'name and docstring are kept'),
('calls = []\n@retry(3)\ndef bad():\n calls.append(1)\n raise ValueError(len(calls))\ntry:\n bad()\nexcept ValueError as e:\n result = e.args[0]', 3, 'the last error is raised'),
('calls = []\n@retry(1)\ndef bad():\n calls.append(1)\n raise OSError\nresult = (error_of(bad), len(calls))', ('OSError', 1), 'one call only'),
('calls = []\n@retry(4)\ndef ok():\n calls.append(1)\n return 1\nok()\nresult = len(calls)', 1, 'no retry after success'),
]