Write decorators that preserve function metadata
Why you care
Every decorator tutorial shows you how to add timing or logging. What none of them warn you about is that a decorator without functools.wraps silently renames the function it wraps. Your audit log starts showing "wrapper" instead of "load_orders". Your docstrings disappear. Introspection tools, type checkers and monitoring dashboards all use __name__ and __doc__ — lose them and you spend twenty minutes per incident trying to figure out which "wrapper" in the stack trace crashed. Interviewers ask "what does functools.wraps do?" because it is the single line that separates a toy decorator from a production one, and forgetting it is a 3-year developer's most common decorator mistake.
Explain like I'm 5
Think of a decorator as a new coat of paint on a car. The car still drives the same, but if the painter forgets to keep the old number plate, the DMV has no idea whose car it is. functools.wraps is the instruction to the painter: keep the original plate, keep the VIN sticker, keep the service history. Without it you have a car nobody can identify.
Core concept
A decorator is any callable that takes a function and returns a callable. The minimal form is a three-layer stack: the outer function receives the target, defines a wrapper, and returns it.
functools.wraps(func)assigns__module__,__name__,__qualname__,__doc__,__annotations__and__type_params__(3.12+) fromfunconto the new wrapper, and updates the wrapper's__dict__with the original's. It also sets__wrapped__to point directly at the original.__wrapped__lets callers bypass all decoration layers:f.__wrapped__(*args)calls the bare function.- Stacking order: decorators apply bottom-up at definition, but execute outer-to-inner at call time. If
@Asits above@B,A's wrapper runs first when you call the function. - When you stack two decorators, both must use
functools.wrapsor the outermost's name will win and the inner one's name is lost.
Decision rule: use functools.wraps on every wrapper you write, with no exceptions. The only time you intentionally skip it is when you are writing a decorator that changes the function's public identity (a rare rename-on-purpose pattern), and even then you set __wrapped__ manually.
Minimal example Metadata loss without wraps, and the fix
import functools
def without_wraps(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
def with_wraps(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@without_wraps
def load_orders(path):
"""Load orders from CSV."""
@with_wraps
def load_settlements(path):
"""Load settlements from CSV."""
print(load_orders.__name__)
print(load_orders.__doc__)
print(load_settlements.__name__)
print(load_settlements.__doc__)
print(load_settlements.__wrapped__ is load_settlements)wrapper
None
load_settlements
Load settlements from CSV.
FalseIn production Audit decorator for ETL steps
import functools
def audit(func):
"""Record name and row count for every ETL step."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"[audit] {func.__name__} starting")
result = func(*args, **kwargs)
count = len(result) if isinstance(result, (list, tuple)) else "n/a"
print(f"[audit] {func.__name__} done rows={count}")
return result
return wrapper
@audit
def extract_orders(source: str) -> list:
"""Pull orders from an S3 key and return raw dicts."""
return [{"id": i, "amount": i * 100} for i in range(1, 4)]
@audit
def extract_settlements(source: str) -> list:
"""Pull settlements; returns empty when source is missing."""
return []
extract_orders("s3://bucket/orders.csv")
extract_settlements("s3://bucket/settlements.csv")
print(extract_orders.__name__)
print(extract_orders.__wrapped__.__name__)[audit] extract_orders starting
[audit] extract_orders done rows=3
[audit] extract_settlements starting
[audit] extract_settlements done rows=0
extract_orders
extract_ordersSee it happen Decoration builds a chain; calls execute outer-to-inner
- Build time: @tag_step wraps the body first, becoming the innermost layer.
- Build time: @audit then wraps the @tag_step layer. The ETL script sees only @audit.
- Call time: the caller invokes @audit, the outermost wrapper.
- @audit runs its before-code, then hands control down to @tag_step.
- @tag_step runs, then calls the body. Return values travel back left through the same chain.
In your world
The situation
Your nightly Jenkins job runs extract_orders(), which is wrapped in a home-grown @timed decorator that was copy-pasted from a blog post. After a production alert, you notice the monitoring dashboard shows all slow functions as "wrapper", not their real names, and the docstrings are gone from the auto-generated runbook.
What actually breaks
Every @timed-decorated function appears as "wrapper" in logs, stack traces and the runbook. The on-call engineer cannot tell from the log which step was slow. When the runbook tool reads func.__doc__, it gets None for every step.
What you'd do on Monday
Add @functools.wraps(func) inside every decorator that defines a wrapper. It is a one-line change per decorator and takes no time to test. Add a unit assertion to every decorator's test suite:
import functools, unittest
def timed(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
class TestTimedDecorator(unittest.TestCase):
def test_metadata_preserved(self):
@timed
def load(): """Load rows."""
self.assertEqual(load.__name__, "load")
self.assertEqual(load.__doc__, "Load rows.")
self.assertIs(load.__wrapped__, load.__wrapped__)Imagine you work at Uber
The numbers
Illustrative: 15M events/day ÷ 86,400 s ≈ 174 events/s average, spiking to ~1,000/s during peak hours. A decorator that builds a log string with f"[{func.__name__}]" costs roughly 0.5 µs per call. At 1,000 calls/s that is 0.5 ms/s, a rounding error. But if the decorator calls inspect.stack() to capture the caller's filename and line number, each call costs ~40 µs. At 1,000 calls/s that is 40 ms/s per worker process; across 20 workers that is 800 ms CPU spent on introspection every second.
What the Scenario-A answer does here
The Scenario A fix (adding functools.wraps) keeps decorator overhead at the µs level with no change to call cost. The metadata problem is purely a correctness fix, not a performance one.
What flips at this scale
The question at scale is not functools.wraps itself but what you put inside the wrapper. Any I/O, stack inspection or lock acquisition inside a hot-path decorator multiplies by call volume. At 1,000 calls/s per worker, every 1 ms of wrapper overhead costs 1 s of CPU per second per worker: a 100% overhead.
The trade-off you'd defend
I would defend a flat decorator that appends to a ring buffer and a background thread that flushes the buffer, trading some delay in log delivery for keeping wrapper overhead under 2 µs. Stack inspection stays behind a debug feature flag and is never on in production.
Illustrative figures chosen to make the arithmetic visible; not Uber-published data.
Gotchas
Monitoring dashboard shows "wrapper" for every function
Log lines and traces all say func=wrapper instead of the function's real name. func.__doc__ is None.
The decorator uses a plain inner function without @functools.wraps(func).
Add @functools.wraps(func) as the first line inside every decorator that defines a wrapper closure.
A cached method holds its instance alive forever
After del obj, the object is never garbage-collected; memory grows without bound.
@functools.lru_cache on an instance method uses self as part of the cache key, storing a strong reference to every instance that has called it.
Move the cached logic to a module-level function that accepts only plain hashable arguments, or use functools.cached_property (per-instance, collected with the instance) for simple attribute caching.
__wrapped__ skips all validation
Calling func.__wrapped__(bad_arg) bypasses guards added by outer decorators such as input validation or rate limiting.
__wrapped__ is a direct reference to the original; it is intentional but easy to misuse.
Treat __wrapped__ as a test or introspection handle only, never as the runtime call path in production code.
Tricky questions
Yes, the decorator wraps it so the docstring comes through.
Only if the decorator uses functools.wraps. Without it, func.__doc__ returns the wrapper's docstring, which is usually None. The wrapper is a distinct callable with no relationship to the original unless you explicitly copy attributes.
load_settlements.__wrapped__ is load_settlements true?Yes, __wrapped__ points back to itself because the wrapper knows its own name.
False. __wrapped__ points to the original unwrapped function, which is a different object. load_settlements is the wrapper; load_settlements.__wrapped__ is the pre-decoration callable. You can verify with type(load_settlements.__wrapped__).
Scenario question
You're handed a Python codebase where @functools.lru_cache is applied to an instance method. A profiler shows the process slowly consumes memory over a day until the container is OOM-killed. The method is only called with small integer arguments. What is happening and how do you fix it?
Model answer
I would check whether self is part of the cache key. lru_cache caches based on all arguments including self, so every distinct instance that calls the method gets its own cache entry and the instance is held alive as long as that entry lives. With maxsize=128, 128 instances are pinned at all times; if the cache fills and the evicted instance has no other references it is freed, but instances are created faster than the LRU evicts them. I would fix this by moving the computation to a module-level function that takes only the plain integer arguments, and have the method call that function. The trade-off is that the cache is now shared across all instances, which is almost always what you want for a pure lookup.
Interview corner
CommonWhat does functools.wraps do, and why does it matter?
TrickYou apply two decorators. Which one's __name__ do you see on the wrapped function?
Experience checkWhen did missing functools.wraps hurt you in real code?
CommonWhat does func.__wrapped__ give you?
Memory hook
A decorator without functools.wraps is a new coat of paint with the number plate scraped off. The car runs the same, but nobody can identify it in a crash.
Every wrapper must carry @functools.wraps(func) or your monitoring dashboard will lie to you.
Self-check
What attribute does
functools.wrapsset to link the wrapper back to the original?__wrapped__. It points at the original undecorated callable.If
@Asits above@Bin the source, which wrapper runs first when the function is called?Aruns first. Decorators apply bottom-up at definition but execute outer-to-inner at call time.What does
func.__name__return when the decorator omitsfunctools.wraps?"wrapper"— the inner function's literal name, not the decorated function's name.
Write a decorator @timed that records elapsed time but intentionally omits functools.wraps. Apply it to def load_csv(path): """Load a CSV file.""" return []. Print load_csv.__name__ and load_csv.__doc__. Then add @functools.wraps(func), repeat, and confirm the output changes from wrapper / None to load_csv / Load a CSV file.. Paste both outputs.