A decorator factory accepts configuration and returns a decorator, which then produces the wrapped function.
Separate configuration time from call time and implement a retry policy with a clear attempt budget and failure behavior.
One source needs two attempts; another needs five. Passing that setting to a
decorator adds a separate moment of work: build a configured decorator, apply
it to a function, and later run the wrapper. Follow those three calls before
implementing retries, where exhausting the budget must preserve the failure
rather than silently return None.

Configure a retry for a flaky source
@something above a def means func = something(func). Here something is
the whole expression after the @ — retry(times=3) — evaluated first, and
its result has to itself be a decorator. So retry isn't a decorator; it's a
function that builds one. Written without the @:
decorate = retry(times=3) # 1. the factory runs, returns a decorator
fetch_export = decorate(fetch_export) # 2. the decorator runs, returns a wrapper
fetch_export("feed-7") # 3. later: the wrapper runs, on every callThree calls, three nested closures:
wrapper reads func from decorate's cell and times from retry's cell —
the setting written on the @ line is still sitting in a cell every time the
wrapper runs.
Preparing this topic’s interactive investigation…
The retry that forgot its parentheses
def retry(times):
def decorate(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
return decorate
@retry
def fetch(source):
return f"rows from {source}"
print(type(fetch("s3")).__name__)That bug doesn't crash — it returns a function where you expected rows, and the
failure turns up stages later. Once a decorator takes settings, the @ line
always has parentheses, even when every setting has a default: @retry().
log = []
def retry(times):
log.append(f"factory({times})")
def decorate(func):
log.append("decorate")
def wrapper(*args, **kwargs):
log.append("call")
return func(*args, **kwargs)
return wrapper
return decorate
@retry(2)
def a(): return 1
@retry(5)
def b(): return 2
a(); a(); b()
print(len(log), log.count("call"))A retry that gives up quietly is worse than none
This code is broken. Run it, read the error, then fix it.
None passes silently into the next stage — Quarry would write an empty
report while telling everyone the run succeeded. A retry wrapper has exactly
two honest outcomes: return a real result, or raise the error it couldn't get
past.
Define an attempt budget before adding backoff
Here times=3 means three total attempts, not one attempt plus three retries.
For a source that fails twice and then succeeds, the wrapper makes three calls
and waits between the first and second, then between the second and third.
There is no wait after success or after the final failure.
| Attempt | Outcome | Next action with a budget of 3 |
|---|---|---|
| 1 | SourceDown |
Record attempt; optionally wait; try again |
| 2 | SourceDown |
Record attempt; optionally wait; try again |
| 3 | Success | Return the result immediately |
| 3 instead | SourceDown |
Re-raise that failure; no fourth call |
Validate a production budget as an integer of at least one. A zero-length loop
cannot have a “last error” to raise. The exercises supply positive budgets;
rejecting invalid configuration is an additional contract, not silently
returning None. Reset per-call attempt counters inside wrapper, while keeping
configuration in the factory's captured state.
Retries also repeat side effects. A timeout after a server accepted a write
does not prove the write failed; repeating it can create duplicates. Use this
wrapper for the simulated read, and require an idempotency policy before using
it for a write. For the backoff exercise, inject a recording sleep function
rather than make tests actually wait. With base 0.5, factor 2, and three
failed attempts before success, predict [0.5, 1.0, 2.0] and then check the log.
One-liner: retry only what's worth retrying
The except clause above catches SourceDown, not Exception. That's
deliberate — a TypeError from a real bug in the stage fails identically on
every attempt, so retrying it just triples the wait before someone sees the
traceback. A real retry wrapper takes the exception types as a setting too:
@retry(times=3, on=(SourceDown, TimeoutError)) — you'll write that one in the
exercises.
Watching three layers collapse into one call site
Step through it. The factory and decorator frames open and close once, while
the module is being defined. After that, each call goes straight into
wrapper, which still reaches times and func through its cells:
Here is the same thing as a picture. Settings flow in from the top, and the function you actually call is the innermost layer:
Decorator expressions are evaluated top-down; the resulting decorators are applied bottom-up. Distinguish constructing a configured decorator from applying it:
@log_calls # 3rd: wraps everything below
@retry(times=3) # its returned decorator wraps timed(...) second
@timed # 1st: wraps the original
def fetch_export(source): ...Quick practice
Stacked decorators apply bottom-up, same as a single one: the layer nearest
the def wraps first and ends up innermost.
order = []
def log_calls(func):
def wrapper(*a, **kw):
order.append("log")
return func(*a, **kw)
return wrapper
def retry(times):
def decorate(func):
def wrapper(*a, **kw):
order.append("retry")
return func(*a, **kw)
return wrapper
return decorate
def timed(func):
def wrapper(*a, **kw):
order.append("timed")
return func(*a, **kw)
return wrapper
@log_calls
@retry(times=3)
@timed
def fetch_export(source):
order.append("fetch")
return source
fetch_export("x")
print(order)TypeErrorRun it and read which argument is missing. The decorator needs a setting — supply one.
class Flaky(Exception):
pass
def retry(times):
def decorate(func):
def wrapper(*a, **kw):
last = None
for attempt in range(times):
try:
return func(*a, **kw)
except Flaky as err:
last = err
raise last
return wrapper
return decorate
tries = [0]
@retry(times=3)
def fetch():
tries[0] += 1
if tries[0] < 2:
raise Flaky("down")
return "ok"
print(fetch(), tries[0])🎯 Your turn
Write retry(times), a decorator factory. Its wrapper calls the function up to
times times, catching SourceDown. It returns the first success, and if
every attempt fails it re-raises the last error. It also records how many
attempts the most recent call made, as wrapper.attempts.
Then write retry_outcome(times, failures). It wraps make_flaky(failures)
(provided — a fetcher that fails its first failures calls) with
retry(times), calls it once with "feed", and returns
{"result": ..., "attempts": ...} — the fetched text, or "gave up" if
SourceDown escaped:
retry_outcome(3, 2)→{"result": "rows from feed", "attempts": 3}retry_outcome(2, 5)→{"result": "gave up", "attempts": 2}
Hint: three layers — retry(times) returns decorate(func) returns
wrapper(*args, **kwargs). Reset wrapper.attempts = 0 at the start of each
call.
Press ▶ Run, then ✓ Check. ✅
Practice — level up
0/6 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Write a decorator factory repeat(n) whose wrapper calls the function n times and returns a list of the results. Then repeat_word(n, word) returns repeat(n)(echo)(word), where echo(word) returns word.
Write with_prefix(prefix), a decorator factory whose wrapper returns prefix + ": " + result. Use it with @with_prefix("WARN") on a function warn(msg) that returns msg.strip(). warn_line(msg) returns warn(msg).
Write clamped(low, high), a decorator factory that forces a function's numeric result into [low, high]. Then clamp_reading(low, high, value) returns clamped(low, high)(calibrate)(value), where calibrate(v) returns v * 1.5.
Write retry(times, on): retry up to times attempts, but only for exceptions whose class is in the tuple on; anything else escapes immediately. retry_log(errors, times) wraps a provided stage that raises the named exceptions in order ("SourceDown" or "ValueError") and then returns "ok", retrying only SourceDown. Return {"result": ..., "attempts": ...}, where result is "ok" or the escaping exception's class name.
Write retry(times, base, factor, sleep): between failed attempts, the wrapper calls sleep(wait), starting at base and multiplying by factor each time (no sleep after the final attempt). Retry only SourceDown. backoff_waits(times, base, factor, failures) uses a recording sleep (it appends each wait to a list), wraps make_flaky(failures), calls it once, and returns {"result": text or "gave up", "waits": [...]}.
@timed needs two nested functions, but @retry(times=3) needs three. Explain why, saying what each layer receives, when each one runs, and what would go wrong if you wrote @retry without the parentheses.