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.

Don't repeat yourself

Here is our decorator from the previous page again:

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:

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

gift = christmas_decorator(gift)

gift()

In the code above, you might notice yourself saying gift over and over. As much as I love gifts, let’s try to reduce the repetition.

In Python, you can save yourself from typing gift = christmas_decorator(gift) by annotating gift() with @christmas_decorator instead. So the following code is the same as the above.

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

gift()

Try this out yourself! You will see that your gift will be Christmas-ready! πŸŽ„πŸŽ