📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials Python from Zero Decorators

Decorators

6 min read Quiz at the end
Decorators wrap functions to add behaviour without changing their code. Use @decorator_name above the function. Built-in decorators include @staticmethod, @classmethod, and @property. Use @functools.wraps inside custom ones.

Function Decorators

import time

def timer(fn):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = fn(*args, **kwargs)
        print(f"{fn.__name__} took {time.time()-start:.4f}s")
        return result
    return wrapper

@timer
def slow_function():
    time.sleep(1)

slow_function()  # slow_function took 1.0003s
Topic Quiz · 5 questions

Test your understanding before moving on

1. What is a decorator?
💡 A decorator is a function that takes a function and extends or modifies its behaviour.
2. Which symbol applies a decorator?
💡 The @ symbol applies a decorator: @my_decorator before a function definition.
3. What does @functools.lru_cache do?
💡 @lru_cache caches function results to avoid repeated expensive computations.
4. What does @staticmethod do?
💡 @staticmethod creates a method that doesn't receive self or cls.
5. What does @classmethod receive as first arg?
💡 @classmethod methods receive the class (cls) as the first argument.