← All Exercises
Retry Decorator with Exception Filtering
intermediatepython
Background
Retry logic belongs in one reusable place; decorators keep call sites clean while functools.wraps preserves metadata for debugging.
Problem
Write a retry decorator factory retry(times=3, exceptions=(Exception,), delay=0.0, sleep=time.sleep). It calls the wrapped function up to times, retries only instances of exceptions, waits delay * 2**attempt between tries, and re-raises the last matching exception after the final attempt.
Input
Decorator parameters (attempt budget, exception tuple, base delay) and a wrapped callable.
Output
The wrapped function's return value on success, or the last matching exception after all attempts.
Sample tests
Sample 1
Input: a function raises ValueError twice, then returns 42; retry(times=3, exceptions=(ValueError,), delay=0, sleep=noop)
Expected: 42
Sample 2
Input: a function raises KeyError immediately; retry(times=3, exceptions=(ValueError,))
Expected: KeyError raised immediately
Your solution
Learning objective
Centralize retry policy in a decorator with an explicit exception allowlist and exponential backoff.