Skip to main content
🔒 Preview mode. The first 15 Foundations lessons are free; this one is Pro. Start a 7-day trial to unlock the editor, AI hints and the rest of the curriculum. Card required, cancel any time in Dashboard.Start 7-day trial →
← CoursesSenior Deep-DivesModule 9 · Error handling depthRetry decorator — bounded attempts + exponential backoff + targeted catchpredict140 / 161
+150 XP
Task
📝 **Task:** Predict the exact 6-line output. A `retry` decorator with `max_attempts=4, base_delay=1, retry_on=(ValueError,)` wraps `flaky()`. The function fails on attempts 1 and 2 (raising ValueError) and succeeds on attempt 3 (returning 'ok'). The decorator logs each attempt + the sleep that would happen. Predict the result print, the call counter, and the log lines. 📋 Implement the function above. Tests run automatically. 💡 **Hint:** Re-read the theory if you get stuck.
Predict the output

Read the code carefully

from functools import wraps


attempts_log: list[str] = []


def retry(max_attempts: int = 3, base_delay: float = 0, retry_on: tuple = (Exception,)):
    def decorator(fn):
        @wraps(fn)
        def wrapper(*args, **kwargs):
            attempt = 0
            while True:
                attempt += 1
                try:
                    return fn(*args, **kwargs)
                except retry_on as e:
                    attempts_log.append(f"attempt {attempt} failed: {type(e).__name__}")
                    if attempt >= max_attempts:
                        attempts_log.append("giving up")
                        raise
                    # In real code: time.sleep(base_delay * (2 ** (attempt - 1)))
                    # Here we log the would-be sleep for the predict trace.
                    attempts_log.append(f"sleep {base_delay * (2 ** (attempt - 1))}")
        return wrapper
    return decorator


calls = [0]


@retry(max_attempts=4, base_delay=1, retry_on=(ValueError,))
def flaky() -> str:
    calls[0] += 1
    if calls[0] < 3:
        raise ValueError(f"fail #{calls[0]}")
    return "ok"


result = flaky()
print(f"result: {result}")
print(f"calls: {calls[0]}")
for line in attempts_log:
    print(line)

What will the program print? Write here:

💬 Discussion

Be the first to ask a question or share a tip.
Sign in to join the discussion. Reading is free.
Loading discussion…