Decorators
Transform functions with decorators: the @ syntax, functools.wraps, and practical decorator patterns.
What you'll learn
- Understand functions as first-class objects
- Write and apply decorators with @ syntax
- Use functools.wraps to preserve metadata
- Create decorators with arguments
- Apply practical decorator patterns
Concept
Functions Are Objects
In Python, functions are first-class objects — they can be assigned to variables, passed as arguments, and returned from other functions. This is the foundation of decorators:
def greet(name):
return f"Hello, {name}!"
say_hello = greet # assign function to a variable
print(say_hello("Ada")) # Hello, Ada!
def call_twice(func, value):
return func(value) + " " + func(value)
print(call_twice(greet, "Ada")) # Hello, Ada! Hello, Ada!
Because functions are objects, you can write functions that modify other functions. A decorator is exactly that — a function that takes a function and returns a new (wrapped) function.
Basic Decorator
def uppercase_result(func):
def wrapper():
result = func()
return result.upper()
return wrapper
def greet():
return "hello, world!"
greet = uppercase_result(greet) # manually decorate
print(greet()) # HELLO, WORLD!
The decorator uppercase_result takes greet, and returns a new wrapper function that calls greet and uppercases the result. The original greet is replaced by the wrapped version.
The @ Syntax
The @ symbol is syntactic sugar for applying a decorator:
@uppercase_result
def greet():
return "hello, world!"
# This is exactly equivalent to:
# def greet():
# return "hello, world!"
# greet = uppercase_result(greet)
print(greet()) # HELLO, WORLD!
The @decorator line above a function definition applies the decorator immediately after the function is defined. This is the standard way to use decorators.
Decorators with Arguments
To pass arguments to the decorator itself, you need an extra level of nesting:
def repeat(n):
def decorator(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return result * n
return wrapper
return decorator
@repeat(3)
def greet(name):
return f"Hello, {name}! "
print(greet("Ada")) # Hello, Ada! Hello, Ada! Hello, Ada!
repeat(3) returns a decorator, which wraps the function. The *args, **kwargs in wrapper ensures the wrapped function accepts any arguments.
functools.wraps — Preserve Metadata
When you wrap a function, the wrapper replaces the original's __name__, __doc__, and other metadata. Use functools.wraps to preserve them:
from functools import wraps
def log_calls(func):
@wraps(func)
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}({args}, {kwargs})")
result = func(*args, **kwargs)
print(f"{func.__name__} returned {result}")
return result
return wrapper
@log_calls
def add(a, b):
"""Add two numbers."""
return a + b
print(add.__name__) # 'add' (preserved by @wraps)
print(add.__doc__) # 'Add two numbers.' (preserved)
print(add(2, 3))
# Calling add((2, 3), {})
# add returned 5
# 5
Always use @wraps(func) in your decorators — without it, debugging becomes harder because all wrapped functions show up as wrapper instead of their real names.
Practical Decorator: Timing
import time
from functools import wraps
def timed(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
elapsed = time.perf_counter() - start
print(f"{func.__name__} took {elapsed:.4f}s")
return result
return wrapper
@timed
def slow_function():
time.sleep(1)
return "Done"
slow_function() # slow_function took 1.0012s
Stacking Decorators
You can apply multiple decorators — they are applied bottom-up:
@decorator_a
@decorator_b
def func():
pass
# Equivalent to: func = decorator_a(decorator_b(func))
The decorator closest to the function is applied first. decorator_b wraps func, then decorator_a wraps the result.
Built-in Decorators
Python has several built-in decorators you will encounter:
@staticmethod/@classmethod— in classes@property— computed attributes@functools.lru_cache— memoization (cache results)@dataclass— auto-generate class boilerplate
from functools import lru_cache
@lru_cache(maxsize=128)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(100)) # fast — results are cached
@lru_cache is one of the most useful built-in decorators — it caches function results to avoid recomputation, turning an exponential Fibonacci into a linear one.
Example
import time
from functools import wraps
# Basic decorator
def uppercase_result(func):
@wraps(func)
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return result.upper()
return wrapper
@uppercase_result
def greet(name):
"""Greet someone."""
return f"hello, {name}!"
print(greet("Ada")) # HELLO, ADA!
print(greet.__name__) # greet (preserved by @wraps)
# Decorator with arguments
def repeat(n):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs) * n
return wrapper
return decorator
@repeat(3)
def say(word):
return word + " "
print(repr(say("Hi"))) # 'Hi Hi Hi '
# Practical: timing decorator
def timed(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
elapsed = time.perf_counter() - start
print(f" {func.__name__} took {elapsed:.6f}s")
return result
return wrapper
@timed
def compute():
total = sum(x ** 2 for x in range(10000))
return total
print(f"Result: {compute()}")
# Built-in: lru_cache for memoization
from functools import lru_cache
@lru_cache(maxsize=128)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
print(f"Fibonacci(30) = {fibonacci(30)}") # fast — cached
# Stacking decorators
@uppercase_result
@timed
def get_message():
return "hello from the function"
print(get_message())
Shows a basic decorator with @wraps, a decorator factory with arguments, a practical timing decorator, the built-in @lru_cache for memoization, and stacked decorators applied bottom-up.
Try it
- JSON Formatter
Decorators are used in web frameworks to format JSON responses.
- Regex Tester
Decorators can cache compiled regex patterns for performance.
Common mistakes
The mistake
Forgetting @wraps(func) and losing the original function's name and docstring
The fix
Without @wraps, the wrapped function's __name__ becomes 'wrapper' and __doc__ is lost, making debugging and help() useless. Always use @functools.wraps(func) on the wrapper function inside your decorator.
The mistake
Not using *args, **kwargs in the wrapper, so it only works with no-argument functions
The fix
The wrapper must accept *args, **kwargs and pass them through to func(*args, **kwargs). Without this, the decorator only works on functions with no parameters, limiting its usefulness.
Related Resources
Related Cheatsheets
- Python Cheatsheet
Decorator syntax, @wraps, and common decorator patterns.
Practice Decorators
2 exercises
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.