This is an archived version of the course and is no longer updated. Please find the latest version of the course on the main webpage.

Chaining decorators

You can also decorate a function with multiple decorators. They will be executed in the order that they are listed.

What do you think the output for the code below will be? Verify it!

def html(func):
    def wrapper(*args, **kwargs):
        print("<html>")
        func(*args, **kwargs)
        print("</html>")
    return wrapper

def body(func):
    def wrapper(*args, **kwargs):
        print("<body>")
        func(*args, **kwargs)
        print("</body>")
    return wrapper

@html
@body
def text_printer(text):
    print(text)

text_printer("This is my text")

The decorated function will be equivalent to:

text_printer = html(body(text_printer))

What happens when you swap the order of decorators? Guess, and then verify!

@body
@html
def text_printer(text):
    print(text)

text_printer("This is my text")