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

Chapter 2: Python decorators

Don't repeat yourself

face Josiah Wang

Here is our decorator from the previous page again:

1
2
3
4
5
6
def christmas_decorator(func):
    def wrapper():
        print("wrapping")
        func()
        print("with a Christmas-y wrapper")
    return wrapper

And we have decided that our gift should always be wrapped for Christmas:

1
2
3
4
5
6
def gift():
    print("a toy")

gift = christmas_decorator(gift)

gift()

In the code above, you might notice yourself saying gift over and over. Line 4 alone has two mentions of gift! As much as I love gifts, let’s try to reduce the repetition.

In Python, you can replace Line 4 by annotating gift() with @christmas_decorator instead. So the following code is the same as the one above.

1
2
3
4
5
@christmas_decorator
def gift():
    print("a toy")

gift()

Try this out yourself! You will see that your gift will be Christmas-ready! 🎄🎁

As a summary, a @decorator on a func_name() is a cleaner way of writing func_name = decorator(func_name)! That’s it really!