Lesson 12: Decorators — Wrapping Functions
A decorator is a function that takes another function and returns a new function, usually a wrapped version of the original with some extra behaviour. You have already used decorators in this course — @classmethod, @staticmethod and @contextmanager are all decorators — but now it is time to write your own. The syntax is the @ sign above a function definition, which is simply shorthand: writing @timer above def work() is exactly the same as writing work = timer(work) afterwards.
The classic first decorator is a timer. It wraps any function, records the time before and after calling it, prints how long it took, and returns the result unchanged. The wrapper needs *args and **kwargs so it can accept whatever arguments the original function accepts, and it needs functools.wraps so the wrapped function keeps its original name and docstring — without that, every decorated function would mysteriously report its name as wrapper, which makes debugging miserable.
import functools
import time
def timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
print(f"{func.__name__} took {time.perf_counter() - start:.3f}s")
return result
return wrapper
@timer
def slow_add(a, b):
time.sleep(0.1)
return a + b
print(slow_add(2, 3)) # prints the timing, then 5
print(slow_add.__name__) # slow_add — thanks to functools.wraps
Decorators with arguments, and stacking
A decorator can itself take arguments, which means writing a function that returns a decorator — one more level of nesting. A @repeat(3) decorator, for example, would call the wrapped function three times. You can also stack decorators: @timer above @cache above a function applies them from the bottom up, so the function is first cached and then timed. Order matters, and thinking through which wrapper runs first is a good exercise in reading code inside out.
Decorators are everywhere in real Python. Web frameworks use them to mark a function as a route; test frameworks use them to mark test functions; functools.lru_cache uses one to memoise a function, remembering past results so repeated calls with the same arguments return instantly. That last one is worth remembering when you meet dynamic programming in the algorithms course — memoisation and lru_cache are the same idea. The guiding rule is that a decorator should add behaviour without changing what the function means: timing, logging, caching and access checks are good fits; silently changing the result is not.
Going further
Decorators are not limited to functions. A class decorator takes a class and returns a modified version of it, and the standard library uses the pattern widely: @dataclass is a class decorator that writes __init__, __repr__ and __eq__ for you from a list of fields. If you have ever wished a simple data-holding class did not need so much boilerplate, dataclasses are the answer — and now you understand the mechanism behind them. The same idea powers web frameworks, where a decorator marks a function as the handler for a web address.
One more decorator deserves a mention because you will meet it in the algorithms course: functools.lru_cache. It memoises a function, remembering the results of past calls so that a repeated call with the same arguments returns instantly instead of recomputing. Applied to a naive recursive Fibonacci, it turns an exponential function into a linear one with a single line of code. The decorator does not change what the function computes — it only remembers — which is exactly the contract a good decorator should keep.
Try writing a decorator of your own that counts how many times a function is called. The wrapper needs a variable that survives between calls, which means storing the count as an attribute on the wrapper function itself — wrapper.calls += 1 — after initialising it to zero. It is a small exercise, but it touches everything in this lesson: closures, *args and **kwargs, functools.wraps, and the idea that a function is an object you can attach data to. Once you have written it, apply it to a recursive function and watch the count climb — you will have built a tiny profiler, and you will understand decorators from the inside.
Watch & Learn
One video to watch for this unit, from a trusted educator.
- Python Tutorial: Decorators - Dynamically Alter The Functionality Of Your Functions — Corey Schafer
Corey builds decorators from first-class functions and closures, showing how to add logging and timing without changing the original function.
Key Terms
- Decorator
- A function that takes a function and returns a wrapped version, adding behaviour without changing the original.
- @ syntax
- Shorthand for applying a decorator: @timer above def work() means work = timer(work).
- Wrapper function
- The inner function a decorator returns; it usually calls the original function and adds behaviour around it.
- *args and **kwargs
- Syntax for accepting any positional and keyword arguments, so a wrapper works for any function.
- functools.wraps
- A decorator that copies a wrapped function's name, docstring and metadata onto the wrapper.
- Stacking decorators
- Applying several decorators to one function; they apply from the bottom up.
- lru_cache
- A standard-library decorator that memoises a function, remembering past results for repeated calls.
Discussion Questions
- Why does a decorator wrapper need *args and **kwargs? What would break if it only accepted the arguments of one specific function?
- What goes wrong if you forget functools.wraps? How would you notice the problem in practice?
- Think of a behaviour you would like to add to many functions at once — logging, timing, retrying. Would a decorator be the right tool? Why?
Practice Questions
- What does
@timerabovedef work()mean, exactly? - Why does the wrapper return
result? - What does
functools.wraps(func)preserve? - If you stack
@timerabove@cache, which wrapper runs first when the function is called? - Write a decorator
shoutthat calls a function returning a string and returns the result in upper case.
Show answers
- It means work = timer(work) after the definition. The @ sign is shorthand for passing the function through the decorator and rebinding the name.
- So the decorated function still returns what the original returned. Forgetting the return would make every decorated function return None.
- The original function's name, docstring and other metadata. Without it, slow_add.__name__ would report "wrapper" instead of "slow_add".
- The timer's wrapper runs first, then the cache's. Decorators apply bottom-up, so the outermost wrapper (timer) is the first to run.
def shout(func): @functools.wraps(func) def wrapper(*args, **kwargs): return func(*args, **kwargs).upper() return wrapperThe wrapper calls the original, then transforms its string result.