Skip to the page

Functions and flow · core

Decorators and writing a retry decorator

A decorator is a function that takes a function and returns a replacement. @d above def f means f = d(f), run once when the function is defined. A decorator with arguments is a factory with three levels.

The notes

What you must know

  • Functions are objects. @d above def f means f = d(f). It runs once at definition time, so decorator code runs at import time.
  • A typical decorator returns a wrapper closure that calls the original with *args, **kwargs.
  • functools.wraps copies name and doc and sets wrapped. Without it, logs, routes and registries see "wrapper".
  • A decorator with arguments is a factory: retry(...) returns decorator(func), which returns wrapper. Stacked decorators apply bottom-up; the top one runs first when called.
  • An async def needs an async wrapper that awaits; otherwise a timer or retry wraps only the creation of the coroutine. inspect.iscoroutinefunction picks the right wrapper.
  • A retry decorator: loop over attempts, catch only the listed exceptions, wait base_delay * 2 ** (attempt - 1) with jitter (random.uniform(0, delay)), and on the last attempt use a bare raise to keep the traceback.
  • Never retry programming errors (TypeError, ValueError) or KeyboardInterrupt. Retry only idempotent calls, or calls that carry an idempotency key. Validate times >= 1 and log each retry.
  • In production use a library such as tenacity, and honour a server Retry-After header.

The red pen

Common traps: mistake → fix

  • Mistake: A decorator runs every time the function is called

    Fix: the decorating line runs once; only the wrapper runs on each call.

  • Mistake: wraps is optional decoration

    Fix: without it names and docs are lost and debugging gets harder.

  • Mistake: Catch Exception for every retry

    Fix: that also retries bugs; list the retryable exceptions.

  • Mistake: time.sleep in an async wrapper is fine

    Fix: it blocks the whole event loop; use await asyncio.sleep.

Easy to hard

Questions interviewers ask, easy to hard

  1. What does @something above a function really do?
  2. Why do we use functools.wraps?
  3. In what order do two stacked decorators run?
  4. Write retry(times=3, on=(TimeoutError,), base_delay=0.5).
  5. How do you make the same decorator work for async functions?

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview