#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):
exceptions, it calls the original again, up to attempts calls in total (the first call included).attempts calls fail, it raises the exception from the last call.__name__ and __doc__.Every call of the decorated function gets its own attempts tries.
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').
attempts is at least 1exceptions is a tuple of exception classesFirst solves only, ranked by stars and then time.