typestar

Decorators with arguments in Python

A decorator factory: one more layer to take parameters.

import functools


def repeat(times):
    def decorator(fn):
        @functools.wraps(fn)
        def wrapper(*args, **kwargs):
            return [fn(*args, **kwargs) for _ in range(times)]
        return wrapper
    return decorator


@repeat(times=3)
def roll():
    return "tumble"


rolls = roll()

How it works

  1. repeat(times) returns the actual decorator.
  2. That decorator wraps the function as usual.
  3. @repeat(times=3) runs the body three times.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
254
Tokens
74
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 42 seconds.

Type this snippet

Step 3 of 5 in Decorators & closures, step 7 of 53 in Pythonic Python.

← Previous Next →