Skip to the solution
MediumDSA10 min read

What is a decorator factory (a decorator with arguments)?

535 views

The problem

Question presented to candidate: "Writing @timer is easy. Now I want @retry(times=3) or @repeat(3), where the decorator takes its own arguments. How do you write that, and what does Python actually do with the @repeat(3) line?"

What a strong answer should cover:

  • @repeat(3) first calls repeat(3), which must return a decorator; that decorator is then applied: f = repeat(3)(f).
  • Three layers: the factory takes the options, the decorator takes the function, the wrapper takes the call arguments; options live in closure cells.
  • Timing: the factory and the decorator both run once at definition time; only the wrapper runs per call.
  • functools.wraps(func) goes on the innermost wrapper.
  • The classic bug of using a factory without parentheses (@repeat), and how to support both @deco and @deco(opt=...) with func=None plus keyword-only options.
  • Alternatives: a class whose __init__ takes the options and __call__ takes the function; standard-library examples such as functools.lru_cache(maxsize=...).

Code / implementation expected: Yes β€” a parameterised decorator such as repeat(n) or retry(times, exceptions), written live.

  • decorators
  • factory

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read Β· 12 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonThree layers, when each runs, reuse, and a retry factory
PythonThe missing-parentheses bug, an optional-argument decorator and a class factory

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 81 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

How does functools.reduce fold a sequence?

Continue