Editor

A Retry Decorator With Arguments

Advanced · Write the code · from 50 Python Practice Problems with Instant Answer Checking (Beginner to Advanced)

From the lesson: 50 Python Practice Problems with Instant Answer Checking (Beginner to Advanced)

Fifty problems, each with a code editor and real tests. Write your solution, press Check, and see exactly which cases pass. Stuck? Hints reveal one at a time, and the solution unlocks once you have checked at least once. Your code and progress are saved in this browser.

Read the lesson

Write retry(times, exceptions=(Exception,)), a decorator factory. The decorated function is called up to times times; if it raises one of exceptions, try again. If the last attempt still fails, re-raise that error. Other exception types must not be retried.

@retry(times=3, exceptions=(ConnectionError,))
def fetch(): ...
import functools
def retry(times, exceptions=(Exception,)):
pass
Solution unlocks after your first Check

What Check runs

Your code runs first, then each of these lines. The output must match exactly.

RunsExpected output
attempts = [] @retry(times=3, exceptions=(ConnectionError,)) def flaky(): attempts.append(1) if len(attempts) < 3: raise ConnectionError("down") return "ok" print(flaky(), len(attempts))ok 3
count = [] @retry(times=2) def always_fails(): count.append(1) raise TimeoutError("still down") try: always_fails() except TimeoutError as e: print("gave up after", len(count), "-", e)gave up after 2 - still down

More practice problems

All Python exercises · 50 practice problems