Imagine you have 20 functions and you want each one to print a log message whenever it runs. You could edit all 20 functions... or you could write the logging logic once and wrap it around any function you like.
That wrapper is called a decorator. You already saw one in the encapsulation chapter: @property. In this chapter you'll learn how decorators actually work and how to write your own.
Step 1: Functions Are Objects
In Python, functions are first-class objects. That means you can store them in variables, pass them to other functions, and return them from functions - just like numbers or strings.
def greet(name):
return f"Hello, {name}!"
say_hello = greet # no brackets: we store the function itself
print(say_hello("Riya"))
def call_twice(func, value):
print(func(value))
print(func(value))
call_twice(greet, "Aman")Output:
Hello, Riya!
Hello, Aman!
Hello, Aman!Notice the difference: greet is the function object, while greet("Riya") calls it.
Step 2: Functions Inside Functions
A function can define another function inside it and return it. The inner function remembers the variables of the outer function even after the outer function has finished. This is called a closure.
def make_multiplier(n):
def multiply(x):
return x * n # n is remembered
return multiply
double = make_multiplier(2)
triple = make_multiplier(3)
print(double(5), triple(5))Output:
10 15These two ideas - passing functions around and closures - are all you need to understand decorators.
Step 3: Your First Decorator
A decorator is a function that takes a function as input, wraps extra behaviour around it, and returns a new function.
def log_call(func):
def wrapper():
print(f"Calling {func.__name__}...")
func()
print("Done")
return wrapper
def say_hi():
print("Hi!")
say_hi = log_call(say_hi) # wrap it manually
say_hi()Output:
Calling say_hi...
Hi!
DoneHere is what happened:
say_hi ---> log_call(say_hi) ---> returns wrapper
wrapper() = print + original say_hi() + print
say_hi now points to wrapperThe @ Syntax
Writing say_hi = log_call(say_hi) is a bit awkward, so Python gives us a shortcut. Putting @log_call above a function means exactly the same thing:
def log_call(func):
def wrapper():
print(f"Calling {func.__name__}...")
func()
print("Done")
return wrapper
@log_call
def say_hi():
print("Hi!")
say_hi()Output:
Calling say_hi...
Hi!
DoneThe decorator runs once, when the function is defined. The wrapper runs every time the function is called.
Decorating Functions with Arguments and Return Values
Our wrapper takes no arguments and ignores the return value, so it breaks for most real functions. The fix is to accept *args and **kwargs (from the function arguments chapter) and return the result.
def log_call(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__} with {args} {kwargs}")
result = func(*args, **kwargs)
print(f"{func.__name__} returned {result}")
return result
return wrapper
@log_call
def add(a, b):
return a + b
total = add(3, b=4)
print("Total:", total)Output:
Calling add with (3,) {'b': 4}
add returned 7
Total: 7This *args, **kwargs pattern works with any function signature, so use it in almost every decorator.
Keep the Original Name with functools.wraps
There is a hidden problem: after decorating, the function "forgets" its own name and docstring, because it is really wrapper now.
from functools import wraps
def plain(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
def proper(func):
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@plain
def first():
"""First docstring."""
@proper
def second():
"""Second docstring."""
print(first.__name__, first.__doc__)
print(second.__name__, second.__doc__)Output:
wrapper None
second Second docstring.@wraps(func) copies the name, docstring and other details from the original function to the wrapper. This matters for debugging, error messages and documentation tools. Always use it.
A Practical Example: Timing a Function
import time
from functools import wraps
def timer(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} seconds")
return result
return wrapper
@timer
def slow_sum(n):
return sum(range(n))
print(slow_sum(10_000_000))Output (the time will differ on your machine):
slow_sum took 0.1532 seconds
49999995000000time.perf_counter() is the recommended clock for measuring short durations.
Decorators That Take Arguments
What if we want @repeat(3)? Now repeat(3) must return a decorator. So we need one more layer:
from functools import wraps
def repeat(times): # 1. takes the argument
def decorator(func): # 2. takes the function
@wraps(func)
def wrapper(*args, **kwargs): # 3. runs on each call
for _ in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(3)
def cheer(name):
print(f"Go {name}!")
cheer("India")Output:
Go India!
Go India!
Go India!@repeat(3) is the same as cheer = repeat(3)(cheer).
Stacking Multiple Decorators
You can apply more than one decorator. They are applied bottom to top (the one closest to the function wraps it first), so when called, the top one runs first.
def bold(func):
def wrapper():
return "<b>" + func() + "</b>"
return wrapper
def italic(func):
def wrapper():
return "<i>" + func() + "</i>"
return wrapper
@bold
@italic
def text():
return "hello"
print(text()) # same as bold(italic(text))()Output:
<b><i>hello</i></b>Useful Built-in Decorators
Decorator | What it does |
|---|---|
| Turns a method into an attribute-like getter (encapsulation chapter) |
| A method that receives neither |
| A method that receives the class ( |
| Copies metadata to a wrapper function |
| Remembers results of previous calls (memoization) |
Memoization with cache
A naive recursive Fibonacci function (you saw recursion earlier) takes exponential time, roughly O(2^n), because it recomputes the same values again and again. One decorator fixes that:
from functools import cache
@cache
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(100))
print(fib.cache_info())Output:
354224848179261915075
CacheInfo(hits=98, misses=101, maxsize=None, currsize=101)Each value from fib(0) to fib(100) is computed only once, so the time drops to O(n). @cache (Python 3.9+) is the same as @lru_cache(maxsize=None). Arguments must be hashable (numbers, strings, tuples - not lists).
Common Mistakes
Forgetting
return wrapper- the decorated name becomesNone, and calling it givesTypeError: 'NoneType' object is not callable.Forgetting
return resultinside the wrapper - the decorated function always returnsNone.Calling the function inside the decorator instead of wrapping it - writing
func()directly in the decorator runs it once at definition time.Mixing up
@repeatand@repeat(3)- a decorator that expects arguments must be called with brackets.Skipping
@wraps- every decorated function shows up aswrapperin logs and tracebacks.
Interview Tips
What is a decorator? A callable that takes a function and returns a new function with added behaviour, without changing the original code.
What does
@decomean?func = deco(func), done once at definition time.Why
functools.wraps? To keep the original__name__,__doc__and other metadata.Real-world uses: logging, timing, caching, retrying, authentication checks (for example
@login_requiredin Django), and route registration (@app.get("/")in FastAPI or@app.route("/")in Flask).Practice: write a
@count_callsdecorator that counts how many times a function was called; write@retry(times)that retries a function when it raises an exception.
Summary
Functions are objects: they can be passed, returned and stored.
A decorator takes a function, wraps it in a new function, and returns the wrapper.
@decois shorthand forfunc = deco(func).Use
*args, **kwargs, return the result, and always add@wraps(func).Decorators with arguments need three levels of functions; stacked decorators apply bottom to top.
A decorator lets you add behaviour to a function without touching its code - write the extra logic once and reuse it everywhere.