Decorators

Functions that take a function and return a better one — and where the stray None in the output comes from.

What you'll learn
  • Use closures, functions as arguments and functions as return values
  • Write a decorator with and without the @ syntax
  • Predict the order in which chained decorators run

A decorator rests on three facts, one per prerequisite script:

def outer(x):                       # 1. inner functions remember enclosing
    def inner(y): return x + y      #    variables: a closure
    return inner
add_five = outer(5); add_five(6)    # 11

def calculate(func, x, y):          # 2. functions are values you can pass
    return func(x, y)

def greeting(name):                 # 3. ...and return
    def hello(): return f"Hello, {name}!"
    return hello

Put them together and you have a decorator: a function that takes a function and returns a wrapped version of it.

def outer(func):
    def inner():
        print('I am decorated!')
        func()
    return inner

@outer                         # same as: original_function = outer(original_function)
def original_function():
    print("I am original!")

The None in the output

Both basic scripts end with print(original_function()), and both print a final None. The wrapper inner calls func() but never returns its result, so the decorated function returns None. A wrapper should pass the result on — return func() — or it silently changes the function it decorates.

Arguments and chaining

smart_divide wraps a two-argument function and guards against dividing by zero. Real decorators accept anything with *args, **kwargs, as the chaining example does:

@star
@percent
def printer(msg):
    print(msg)
Three nested boxes: star.inner outermost, percent.inner inside it, and the original printer in the centre. A call to printer('Hello') enters through star, then percent, reaches print(msg), and returns None outward. The output column shows a row of stars, a row of percent signs, Hello, percent signs, stars, and finally None. Three nested boxes: star.inner outermost, percent.inner inside it, and the original printer in the centre. A call to printer('Hello') enters through star, then percent, reaches print(msg), and returns None outward. The output column shows a row of stars, a row of percent signs, Hello, percent signs, stars, and finally None.
@star over @percent builds printer = star(percent(printer)). The call passes inward through each wrapper and returns outward, so the output nests like the boxes.

The decorator nearest the function is applied first, so printer becomes star(percent(printer)) and the stars end up on the outside.

One line every decorator should have

Wrapping replaces the function’s identity: after decoration, printer.__name__ is 'inner', and its docstring is gone, which confuses debuggers, logs and documentation tools. The standard fix is one decorator on the wrapper:

import functools

def star(func):
    @functools.wraps(func)
    def inner(*args, **kwargs):
        print("*" * 15)
        result = func(*args, **kwargs)
        print("*" * 15)
        return result
    return inner

Try it yourself. Write a @timer decorator that prints how long a function took with time.perf_counter() and returns the function’s result. Then write a decorator factory @repeat(3) — a function that returns a decorator — and check __name__ with and without functools.wraps.

View source on GitHub →