Intermediate Python · Lesson 12 of 14

Decorators

Understand that functions are values, wrap them in other functions, and write decorators that log, count, repeat or cache function calls.

About 17 minutes · code runs in your browser, nothing to install

In Python a function is a value like any other: you can store it in a variable, put it in a list, pass it to another function and return it from one. Decorators build on that idea.

Pythoneditable
def shout(text):
    return text.upper() + "!"

def whisper(text):
    return text.lower() + "..."

def speak(style, text):
    return style(text)

print(speak(shout, "Good morning"))
print(speak(whisper, "Good night"))
print(shout.__name__)
Output
GOOD MORNING!
good night...
shout

Wrapping a function

A decorator is a function that takes a function and returns a new one, usually an inner wrapper that does something extra before or after calling the original. It is a closure, as in Scope and closures.

Pythoneditable
def announce(func):
    def wrapper():
        print("Starting...")
        func()
        print("Finished.")
    return wrapper

def make_tea():
    print("Boiling water, adding leaves")

make_tea = announce(make_tea)
make_tea()
Output
Starting...
Boiling water, adding leaves
Finished.

The @ syntax

Writing @announce on the line above def does exactly the same as make_tea = announce(make_tea), but it is easier to spot. To work with any function, the wrapper takes *args, **kwargs and passes them on, and returns the original's result. functools.wraps copies the original's name and help text onto the wrapper.

Pythoneditable
from functools import wraps

def log_calls(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        parts = [repr(a) for a in args] + [f"{k}={v!r}" for k, v in kwargs.items()]
        print(f"{func.__name__}({', '.join(parts)}) returned {result}")
        return result
    return wrapper

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

@log_calls
def area(width, height=1):
    return width * height

add(2, 3)
area(4, height=5)
print(add.__name__)
Output
add(2, 3) returned 5
area(4, height=5) returned 20
add

Decorators that keep state or take options

A decorator can store data on the wrapper, such as a call counter. To give a decorator its own settings, add one more outer function: @repeat(3) first calls repeat(3), which returns the real decorator.

Pythoneditable
from functools import wraps

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

def repeat(times):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            for _ in range(times):
                func(*args, **kwargs)
        return wrapper
    return decorator

@count_calls
def greet(name):
    return f"Hi {name}"

greet("Ana")
greet("Bo")
print(greet.calls)

@repeat(3)
def cheer():
    print("Hooray!")

cheer()
Output
2
Hooray!
Hooray!
Hooray!

Ready-made decorators

You have already met @property and @dataclass. Another useful one is functools.cache, which remembers the result for each set of arguments, so repeated calls are instant. It turns this slow recursive Fibonacci function into a fast one.

Pythoneditable
from functools import cache

@cache
def fib(n):
    if n < 2:
        return n
    return fib(n - 1) + fib(n - 2)

print(fib(10))
print(fib(80))
print(fib.cache_info().hits)
Output
55
23416728348467685
79
Tip: A common real-world decorator measures how long a function takes with time.perf_counter(). Timings change on every run, so this course only mentions it rather than printing them.

✎ Exercise

Write a decorator require_positive that checks every positional argument. If any is zero or negative, print Rejected: <function name> needs positive numbers and return None; otherwise call the function and return its result.

Hint: Inside the wrapper, any(a <= 0 for a in args) spots a bad value. Use func.__name__ for the name.

Your codewrite your answer, then Run
from functools import wraps

# your code here

@require_positive
def bmi(weight, height):
    return round(weight / height ** 2, 1)

print(bmi(70, 1.75))
print(bmi(70, -1.75))

Expected output:

22.9
Rejected: bmi needs positive numbers
None
Show a solution
Solutioneditable
from functools import wraps

def require_positive(func):
    @wraps(func)
    def wrapper(*args):
        if any(a <= 0 for a in args):
            print(f"Rejected: {func.__name__} needs positive numbers")
            return None
        return func(*args)
    return wrapper

@require_positive
def bmi(weight, height):
    return round(weight / height ** 2, 1)

print(bmi(70, 1.75))
print(bmi(70, -1.75))
Output
22.9
Rejected: bmi needs positive numbers
None

Check yourself

1. What is @announce above def f(): the same as?

2. Why does a general wrapper use *args, **kwargs?

3. What does functools.wraps do?

Spotted a mistake on this page? Tell us