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

Chapter 2: Python decorators

Decorators

face Josiah Wang

Now we are ready to talk about decorators.

Take a look at the example below. Can you understand what it is doing?

Test it out yourself to see whether your guess is correct!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
def christmas_decorator(func):
    def wrapper():
        print("wrapping")
        func()
        print("with a Christmas-y wrapper")
    return wrapper

def gift():
    print("a toy")

print("Before decorating:")
gift()
print(gift) # <function gift at 0x7f12ffd0c1f0>

print("After decorating:")
gift = christmas_decorator(gift)
gift()
print(gift) # <function christmas_decorator.<locals>.wrapper at 0x7f12ffd0c280>

Above is an example of a Python decorator.

  • A Python decorator is a function (Line 1).
  • It takes another function as input (Line 1).
  • It wraps this function and adds more functionality to the function (yes, try saying three functions in one sentence!) (Lines 3-5)
  • It returns the function (Line 6)
  • It reassigns the returned function to the name of the original function (Line 16)

Hopefully it all makes sense!