Editor

Retry on Error

#322 · Functions · Intermediate · 75 XP · about 15 min

Calls to a server or a disk sometimes fail once and then work a moment later. A retry decorator wraps a function so that a failed call is tried again automatically.

Write retry(attempts, exceptions=(Exception,)), a decorator factory used like @retry(3):

  • The decorated function calls the original with the same positional and keyword arguments and returns its result.
  • If that call raises an exception that is an instance of one of the classes in the tuple exceptions, it calls the original again, up to attempts calls in total (the first call included).
  • If all attempts calls fail, it raises the exception from the last call.
  • An exception of any other class is not retried: it passes straight through.
  • The decorated function keeps the original's __name__ and __doc__.

Every call of the decorated function gets its own attempts tries.

Examples

calls = []

@retry(3)
def fetch(page):
    calls.append(page)
    if len(calls) < 3:
        raise ConnectionError('server busy')
    return 'page ' + str(page)

fetch(7)        # returns 'page 7', on the third call
len(calls)      # 3

With @retry(2) instead, the second call would fail too, and fetch(7) would raise ConnectionError('server busy').

Constraints

  • attempts is at least 1
  • exceptions is a tuple of exception classes

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.