Medium: Interview Core · Problem 50 of 82

Call With Retry

MediumErrors and FilesPython

Write call_with_retry(func, attempts) that calls func() (no arguments) and returns its result.

  • If func() raises an exception, call it again, up to attempts calls in total.
  • If every attempt fails, raise the last exception.
  • If attempts is less than 1, raise ValueError without calling func.

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?

  1. Return None
  2. Re-raise the last exception, so the caller learns what went wrong
  3. 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.)