← All lessons

Decorators

Sign in · Sign up

Lesson 11.3

A decorator is a function that wraps another function without changing its code:

def timer(func):
    def wrapper():
        print("Start")
        result = func()
        print("Finish")
        return result

    return wrapper


@timer
def work():
    print("Working")


work()
  • timer takes a function;
  • inside is wrapper, which does something before and after func();
  • return wrapper hands back the wrapper, not its result;
  • @timer is a short way of writing work = timer(work).

The check sets the number limit. Write a decorator repeat(func) whose wrapper calls func twice. Then apply it to the function hello(), which prints Hello!, and call hello().

Hint

A decorator returns a new function, not its result.

Inside repeat declare wrapper, which calls func twice, and return wrapper. The line @repeat does that for you: hello becomes the wrapper — that's why hello() runs twice.