← All lessons

Decorators with arguments

Sign in · Sign up

Lesson 11.4

A decorator with a setting needs three levels of functions:

def repeat(n):
    def decorator(func):
        def wrapper():
            ...          # call func n times

        return wrapper

    return decorator


@repeat(3)
def hello():
    print("Hello!")


hello()
  • repeat(n) is the outer function, it takes the setting argument;
  • decorator(func) is the middle one, it takes the function itself;
  • wrapper() is the inner one, it does the work.

@repeat(3) is hello = repeat(3)(hello): first the setting, then the function. Forgetting one level is a common mistake.

The check sets the number times. Write repeat(n) with three levels and apply it to hello(), which prints Hello!, with @repeat(times). Call hello().

Hint

There are three levels here: repeat(n) → decorator(func) → wrapper().

Each level returns the next one: the setting returns the decorator, the decorator the wrapper. The wrapper repeats the call n times with a for.