Legends ofPythos
Claim your name
Pythonic Python

Decorators

Lesson 7 of 12

Watch the lesson5:56 · with Sigrid
A decorator is a function that takes another function and returns a new one. You use it to add behaviour—like logging or timing—to existing functions without modifying their code.

The basic structure

def my_decorator(func):
    def wrapper():
        print('Before')
        func()
        print('After')
    return wrapper

@my_decorator
def say_hi():
    print('Hi!')

say_hi()
@my_decorator is shorthand for: say_hi = my_decorator(say_hi)
The wrapper function runs the original code, plus your extra logic. The @my_decorator line is short for say_hi = my_decorator(say_hi): after it, the name say_hi points at the wrapper.

Working with any arguments

def my_decorator(func):
    def wrapper(*args, **kwargs):
        print('Before')
        result = func(*args, **kwargs)
        print('After')
        return result
    return wrapper
*args and **kwargs let the wrapper take any arguments, so it works on any function.

Preserving metadata

import functools

def my_decorator(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper

@my_decorator
def say_hi():
    print('Hi!')

print(say_hi.__name__)
@functools.wraps copies the original function's name and docstring to the wrapper.
Every function has a __name__: its name, as text. The last line of the example above prints say_hi. Without the @functools.wraps(func) line, it would print wrapper, the inner function's name. Keeping the real name helps when you're hunting a bug, because error messages and other tools show it.

Keeping state on the wrapper

import functools

def counted(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        # the wrapper can see itself:
        wrapper.call_count += 1
        return func(*args, **kwargs)
    # set the starting value once:
    wrapper.call_count = 0
    return wrapper

@counted
def ping():
    return 'pong'

ping()
ping()
print(ping.call_count)
# 2
A function is an object, so you can hang a value on it.
A function in Python is an ordinary object, so you can attach attributes to it. Set the starting value once, after wrapper is defined but before you return it, and update it inside the wrapper. Because the decorated name now points at wrapper, reading ping.call_count from outside reads that same attribute.

Your turn

0 of 3 solved

Exercise 1

+45 XP
Write a decorator named hello. Its wrapper prints Hello, then calls the decorated function and returns whatever that function returned. Print only Hello: no After line. Keep @hello on the greet function in the starter, so greet() still returns its original value, then call greet() once so Hello is printed.
def hello(func):
    pass




@hello
def greet():
    return "World"

Run your code to check it against the tests.

Exercise 2

+45 XP
Write a decorator called counter that counts how many times the function it wraps has been called, storing the number on the wrapper as .call_count. Write add(a, b) that returns a + b, put @counter above it, then call add twice.
import functools




def counter(func):
    pass

Run your code to check it against the tests.

Exercise 3

+45 XP
Write a decorator called timer that measures how long the function it wraps takes and prints one line in the form Took 0.00s — the word Took, the number of seconds with exactly two decimal places, then the letter s. Use time.time() before and after the call. time.time() gives the time now, in seconds. Inside an f-string's curly brackets, :.2f shows a number with two decimal places. Apply it to the provided slow_sum(n), and call slow_sum(50) so the timing line is printed once. The decorated function must still return its total.
import time


def slow_sum(n):
    total = 0
    for i in range(1, n + 1):
        total += i
    return total

Run your code to check it against the tests.