Call With Retry
Write call_with_retry(func, attempts) that calls func() (no arguments) and returns its result.
- If
func()raises an exception, call it again, up toattemptscalls in total. - If every attempt fails, raise the last exception.
- If
attemptsis less than 1, raiseValueErrorwithout callingfunc.
Understand the problem
Count the calls and think about the final failure.
With attempts=3, func fails every time. How many times is func called?
attempts is the total number of calls, not the number of retries after a first call. Three attempts: three calls, then give up.
After the last attempt fails, what should the function do?
- Return
None - Re-raise the last exception, so the caller learns what went wrong
- Print the error
Swallowing the error and returning None hides the failure, and the caller cannot tell it from a real result. Raise it again: a bare raise inside except re-raises the exception being handled, with its original traceback.
Write the solution
Write the function.
def call_with_retry(func, attempts):
# Write your code here.
pass
Hint 1: a question to ask yourself
How do you remember the last error so that you can raise it after the loop?
Hint 2: the shape of the answer
Check attempts first. Loop attempts times; try: return func(); except Exception as error: last = error. After the loop, raise last.
Reflect
Solution
def call_with_retry(func, attempts):
if attempts < 1:
raise ValueError("attempts must be at least 1")
last_error = None
for _ in range(attempts):
try:
return func()
except Exception as error:
last_error = error
raise last_error
Another way: re-raise inside the last iteration
def call_with_retry(func, attempts):
if attempts < 1:
raise ValueError("attempts must be at least 1")
for attempt in range(1, attempts + 1):
try:
return func()
except Exception:
if attempt == attempts:
raise
What this tests: exceptions in a loop, return inside try, raise and re-raising, and exact counting.
except Exception, not except:: retrying is meant for ordinary errors. KeyboardInterrupt and SystemExit do not inherit from Exception, so a user pressing Ctrl+C is not swallowed.
Variable scope of as error: after the except block Python deletes the name error. That is why the solution copies it to last_error first.
In real code add a short, growing delay between attempts (exponential backoff) and retry only the errors that can heal themselves (a network timeout, not a ValueError). Libraries such as tenacity do this.
What an interviewer might ask next: Add a delay parameter and wait that long between attempts, but not after the last one. (time.sleep(delay) inside the loop except on the final attempt.)
VISIBLE = 3
CASES = [
('calls = []\ndef flaky():\n calls.append(1)\n if len(calls) < 3:\n raise ConnectionError("down")\n return "ok"\nresult = (call_with_retry(flaky, 5), len(calls))', ('ok', 3), 'succeeds on the third try'),
('calls = []\ndef bad():\n calls.append(1)\n raise KeyError("x")\nresult = (error_of(call_with_retry, bad, 3), len(calls))', ('KeyError', 3), 'always fails: raises the error after 3 calls'),
('result = call_with_retry(lambda: 42, 3)', 42, 'works first time'),
('result = error_of(call_with_retry, lambda: 1, 0)', 'ValueError', 'attempts below one'),
('calls = []\ndef bad():\n calls.append(1)\n raise ValueError(len(calls))\ntry:\n call_with_retry(bad, 3)\nexcept ValueError as e:\n result = e.args[0]', 3, 'it is the last error that is raised'),
('calls = []\ndef f():\n calls.append(1)\n return None\nresult = (call_with_retry(f, 3), len(calls))', (None, 1), 'a result of None is a success'),
('calls = []\ndef never():\n calls.append(1)\nerror_of(call_with_retry, never, 0)\nresult = len(calls)', 0, 'with zero attempts func is never called'),
('calls = []\ndef bad():\n calls.append(1)\n raise OSError\nresult = (error_of(call_with_retry, bad, 1), len(calls))', ('OSError', 1), 'one attempt only'),
]