This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 2: Python decorators

Chaining decorators

face Josiah Wang

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!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
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:

1
text_printer = html(body(text_printer))

What happens when you swap the order of decorators? Guess, and then verify! (I won’t give you the output!)

1
2
3
4
5
6
@body
@html
def text_printer(text):
    print(text)

text_printer("This is my text")