Hard: Advanced Interview · Problem 76 of 82

A Retry Decorator

HardDecorators and AdvancedPython

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?

  1. f = retry(f, 3)
  2. decorator = retry(3) then f = decorator(f)
  3. 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?

  1. Only the outermost, retry(times), and the inner layers reach it through closure
  2. The wrapper only
  3. 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.)