Command Palette

Search for a command to run...

Hectal
Phase 9: Iterators, Generators and Decorators
Python · Exercise 5 of 6 PreviousNext
Advanced

Write a retry decorator with settings

Write a decorator factory retry(attempts). The decorated function is called; if it raises ConnectionError it is called again, up to attempts calls in total. If the last attempt also fails, the ConnectionError is raised. Other kinds of error are not retried. The result of a successful call is returned, and arguments are passed through.

Then use it on call_api(prompt), a fake function that fails the first two times and succeeds on the third, and print its answer. (No real waiting or network: this stands in for a flaky model API.)

What Check tests

  1. A function that fails twice then succeeds returns its value
  2. It gives up after attempts calls and raises the error
  3. Other errors are not retried
  4. attempts=1 means one call and no retry
  5. A first-try success calls the function once
  6. The name is kept
  7. The program prints the answer

Stuck? One hint at a time

The solution unlocks after your first Check. Try first: that is where the learning happens.

main.py
Sign in to run your code.

Output

Press Run to see what your program prints.