A Decorator That Takes Arguments

Hard ⏱ 18 min 33% acceptance ★★★★☆ 4.3
Write repeat(times) — a decorator factory: @repeat(3) makes the function run three times per call, returning a list of the results. Three nested functions deep: factory → decorator → wrapper. This nesting is the single most-asked decorator interview question.

Examples

Example 1
Input
@repeat(3) on roll; roll()
Output
a list of 3 results
Explanation

The factory captured times; the wrapper looped.

Constraints

  • Exactly the three-layer structure.
  • Return the list of results.

Topics

Decoratorsdecorator factory

Companies

NetflixUberStripe

Hints

Hint 1

def repeat(times): def decorator(func): def wrapper(...).

Hint 2

Each layer returns the next inner one.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.