Python Decorators: Functions Wrapping Functions, Demystified
How @decorator syntax actually works under the hood, how closures remember state, and why @functools.wraps saves your function metadata.
You'll learn why @something above a def is not magic syntax—it is just passing a function into another function—and how to write reusable decorators with *args, **kwargs, and @functools.wraps. Assumes comfort with Python functions.
1. Functions are just values
In Python, functions are ordinary objects. You can assign a function to a variable, pass it as an argument to another function, and return a brand-new function created inside def:
def shout(fn):
def wrapper():
return fn().upper() + "!"
return wrapper
def greet():
return "hello"
loud_greet = shout(greet)
print(loud_greet())HELLO!loud_greet is wrapper, which remembered fn (greet) from the outer scope (that's called a closure).
Now here is the entire secret behind @ decorators:
@shout
def greet():
return "hello"That @shout syntax is 100% identical to writing greet = shout(greet) right after def greet(). Nothing more, nothing less.
2. Accepting any arguments with *args and **kwargs
Our first wrapper() took zero arguments, so it crashes if you put @shout on def greet(name):.
To build a decorator that works on any function signature, forward all positional and keyword arguments with *args, **kwargs:
import functools
import time
def timed(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = fn(*args, **kwargs)
elapsed = (time.perf_counter() - start) * 1000
print(f"{fn.__name__} took {elapsed:.2f}ms")
return result
return wrapper
@timed
def slow_add(a, b):
"""Adds two numbers very dramatically."""
time.sleep(0.05)
return a + b
print(slow_add(2, 3))slow_add took 50.12ms
5Check print(slow_add.__name__, slow_add.__doc__) with and without @functools.wraps(fn). Without wraps, slow_add.__name__ lies and says "wrapper"!
3. Why @functools.wraps(fn) matters
Without @functools.wraps(fn) on wrapper, replacing slow_add with wrapper erases slow_add.__name__ and its docstring—which breaks debuggers, test runners, and web frameworks like FastAPI or Flask. Always include @functools.wraps(fn).
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
wrapper forgot return result | Decorated function always returns None | Capture result = fn(*args, **kwargs) and return result |
Forgot *args, **kwargs on wrapper | TypeError when decorating functions with parameters | Always accept and forward *args, **kwargs |
Omitted @functools.wraps(fn) | fn.__name__ becomes "wrapper" | Add @functools.wraps(fn) above def wrapper |
Practice
- What is
@my_decoratorabovedef foo():shorthand for?
Answer: foo = my_decorator(foo).
What you learned
@decabovedef fn():is syntactic sugar forfn = dec(fn).- Decorators wrap a function in a
wrapper(*args, **kwargs)closure, run logic before/afterfn(*args, **kwargs), and return its result. - Always use
@functools.wraps(fn)so the wrapped function keeps its real__name__and docstring.
Video walkthrough
YouTubeClick play to load video (YouTube)