A decorator transforms or wraps a function when it is defined, changing the callable that later callers use.
Trace entry, original execution and return through a wrapper while preserving arguments, results and useful function metadata.
Timing belongs around a parsing operation, but copying timing code into every parser makes it hard to maintain. A decorator replaces a function binding with another callable. Use the closures you already know to keep the original function reachable, then follow arguments, results, and exceptions through the wrapper so instrumentation does not change the caller's contract.

Time a stage without touching it
Pasting timing code into every stage drifts and clutters. A decorator writes it once and wraps it around any function instead:
@timed above def parse_row is exactly that reassignment, written once:
The decorator itself runs once, at definition time — not every call:
events = []
def noted(func):
events.append("decorate")
return func
@noted
def parse(row):
events.append("call")
return row
events.append("defined")
parse("x")
print(events)Preparing this topic’s interactive investigation…
Wrap a stage that takes extra arguments
A wrapper written for one argument breaks on anything else:
TypeErrorRun it and read which argument the wrapper choked on. Make the wrapper accept, and forward, any arguments at all.
*args/**kwargs collect anything the caller passed and spread it back out
unchanged — the shape you'll write almost every time. The other classic slip is
forgetting the wrapper has to return the original's result:
def announce(func):
def wrapper(*args, **kwargs):
print("calling", func.__name__, end=" -> ")
func(*args, **kwargs) # called, but the result is thrown away
return wrapper
@announce
def double(n):
return n * 2
print(double(4))Watching one call go through the wrapper
Step through a single call. Watch func and args appear inside wrapper's
frame, the original run, and result come back through the wrapper before the
caller sees it:
Here is the same call as a picture. The wrapper's frame opens around the original and closes after it:
Look at the last value in the trace, though. name_now is "wrapper".
Trace a bug logged as "wrapper"
The decorated name is bound to wrapper, so it looks like wrapper to
anything that asks:
def timed(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@timed
def parse_row(row):
"""Split one CSV row into fields."""
return row.split(",")
print(parse_row.__name__, parse_row.__doc__)@wraps(func), from the standard library, copies metadata and adds __wrapped__, which points to the original:
Treat @wraps(func) as part of the pattern, not an optional extra.
Preserve the call contract, including failure
A transparent wrapper preserves more than the displayed name. Trace four
boundaries: arguments enter the wrapper, enter the original function, a result
or exception leaves the original, and the same outcome reaches the caller.
wraps copies metadata and sets __wrapped__; it does not make these boundaries
correct for you, and the wrapper remains a different function object.
finally runs while the exception passes outward. It records an attempted call,
not a successful parse. Put a return inside finally and you can accidentally
replace the result or suppress the exception. Put after-work only after
result = func(...) and it never runs when the original raises.
The main timing exercise records successful calls. Extend it separately to record every attempt, preserving the original exception. Test a keyword argument, a normal return, and a failing call; a wrapper that only works for one positional success has not yet preserved the function's contract.
One-liner: stacking runs bottom-up
@tag("outer") over @tag("inner") means value = outer(inner(value)) — the
decorator nearest the def wraps first, so it runs innermost.
Quick practice
wrapper.timings = [] runs once, at decoration time, so every decorated
function gets its own list. Inside wrapper, the name wrapper is itself a
free variable — it refers to the function object, which is how a call finds its
own list to append to.
def shout(func):
def wrapper(*a, **kw):
return func(*a, **kw).upper()
return wrapper
def exclaim(func):
def wrapper(*a, **kw):
return func(*a, **kw) + "!"
return wrapper
@shout
@exclaim
def greet(name):
return f"hi {name}"
print(greet("sam"))TypeErrorRun it and read which function the error points at. Make the wrapper accept whatever the original takes.
calls = []
def counted(func):
def wrapper(*args, **kwargs):
calls.append(1)
return func(*args, **kwargs)
return wrapper
@counted
def ping():
return "pong"
ping(); ping(); ping()
print(len(calls))🎯 Your turn
Write the decorator timed(func). Its wrapper must accept any arguments, time
the call with time.perf_counter(), append the elapsed seconds to a list
stored as wrapper.timings, and return the original's result. Use
@wraps(func) so the stage keeps its name.
Then write timed_summary(rows): wrap the provided parse_row with timed,
call the wrapped version once per row, and return
{"name": ..., "calls": ..., "results": [...]} — the wrapped function's
__name__, the number of timings recorded, and each call's result.
timed_summary(["a,b", "c"])→{"name": "parse_row", "calls": 2, "results": [["a", "b"], ["c"]]}
Hint: wrap inside timed_summary (parse = timed(parse_row)) so each run
starts with a fresh, empty timings list.
Press ▶ Run, then ✓ Check. ✅
Practice — level up
0/6 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Write a decorator shouted(func) whose wrapper calls func and returns its result in upper case. Then write shout_greeting(name) that returns shouted(greet)(name), where greet(name) returns f"hello {name}".
Write logged(func): its wrapper appends a line like "square(3)" (the function's name, then the positional arguments' reprs joined by ", ") to a list stored as wrapper.calls, then returns the result. Write call_log(values), which wraps the given square, calls it on each value and returns wrapper.calls.
Write identity_after_wrap(use_wraps). It decorates the provided parse_row with a do-nothing wrapper — using @wraps(func) only when use_wraps is true — and returns [name, doc]: the decorated function's __name__ and __doc__.
Write two decorators: bracket wraps the result in square brackets, exclaim adds "!" to the end. Write stacked_both(word) returning a list of two results for echo(word) (which returns word): first with @bracket above @exclaim, then with @exclaim above @bracket.
Write counted(func): its wrapper increments wrapper.count on each call and returns the result, and it keeps the stage's name via @wraps. Write stage_counts(calls) where calls is a list of [stage_name, text] pairs naming "parse" or "clean". Wrap both provided stages fresh, run each call, and return {"outputs": [...], "counts": {name: count}}, with counts keyed by each wrapped stage's __name__.
A teammate says @wraps is cosmetic and removes it from Quarry's timing decorator to save a line. Explain what actually changes, and give two concrete ways it would hurt a program like Quarry.