Advanced functions and decorators · 3 / 15 Theory

Decorators

A decorator is a function that receives another function and returns an improved version of it, without touching its code. It is built with what you have just learned: functions that receive and return functions.

Building a decorator step by step

We want a function to report when it starts and finishes. We could write the print calls inside each function, or create a decorator that does it for all of them:

def with_notice(function):
    def wrapper(*args, **kwargs):
        print("Starting")
        result = function(*args, **kwargs)
        print("Finished")
        return result
    return wrapper

def add(a, b):
    return a + b

add = with_notice(add)   # we replace add with the wrapped version

print(add(2, 3))
# Starting
# Finished
# 5

The inner function is called wrapper and uses *args and **kwargs to accept any combination of arguments and pass them on to the original function.

The @ syntax

Writing add = with_notice(add) is so common that Python has a shortcut: putting @decorator just above the definition:

@with_notice
def subtract(a, b):
    return a - b

print(subtract(10, 4))
# Starting
# Finished
# 6

Both forms do exactly the same thing. Practice with Decorator that logs calls.

Storing information in the wrapper

Since functions are objects, you can add attributes to them. That way a decorator can keep a count:

def count_calls(function):
    def wrapper(*args, **kwargs):
        wrapper.calls += 1
        return function(*args, **kwargs)
    wrapper.calls = 0
    return wrapper

@count_calls
def greet():
    print("Hello")

greet()
greet()
print(greet.calls)   # 2

Practice with Decorator that counts calls.

A problem: the name is lost

After decorating, the function that really exists is wrapper, so it loses its name and its documentation:

def with_notice(function):
    def wrapper(*args, **kwargs):
        return function(*args, **kwargs)
    return wrapper

@with_notice
def add(a, b):
    """Add two numbers."""
    return a + b

print(add.__name__)   # wrapper
print(add.__doc__)    # None

It is fixed with functools.wraps, which copies the name and the documentation of the original:

from functools import wraps

def with_notice(function):
    @wraps(function)
    def wrapper(*args, **kwargs):
        return function(*args, **kwargs)
    return wrapper

@with_notice
def add(a, b):
    """Add two numbers."""
    return a + b

print(add.__name__)   # add
print(add.__doc__)    # Add two numbers.

It is a good habit to put @wraps(function) in all your decorators.

What are they for in practice?

  • Logging calls or measuring how long a function takes.
  • Checking permissions before running something.
  • Validating the arguments or the result.
  • Saving results already calculated (*caching*), like functools.cache.
  • Web frameworks such as Flask or Django use them to link a function to a web address.