Code

Your First Decorator

Functions are objects: you can pass them around and return them. A decorator is a function that takes a function and returns a new one that usually calls the original with something extra around it.

def announce(func):
    def wrapper(*args, **kwargs):
        print("Casting", func.__name__)
        return func(*args, **kwargs)
    return wrapper

@announce              # same as: spark = announce(spark)
def spark(colour):
    return f"a {colour} spark"

spark("blue")   # prints "Casting spark", returns 'a blue spark'

Three habits make wrappers safe:

  • accept *args, **kwargs so any arguments pass straight through;
  • return the original function's result;
  • return wrapper itself (not wrapper()!) from the decorator.

A wrapper is a function object, so you can even hang attributes on it: wrapper.calls = 0.

Assignment

  1. shout(func): a decorator whose wrapper calls func and returns the result upper-cased.
  2. count_calls(func): a decorator whose wrapper has an attribute calls that starts at 0 and goes up by one every time the decorated function is called. It must still return func's result.