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.

Python Decorators

Now we are ready to talk about Python 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!

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>

So the above is an example of a Python decorator.

  • A Python decorator is a function.
  • It takes another function as input.
  • It wraps this function and adds more functionality to the function (yes, try saying three functions in one sentence!)
  • It returns the function, and reassigns it to the original function