Decorators
A decorator adds something to a function, like logging, timing or retries, without touching the function's own code. This lesson builds one from nothing, one small step at a time, so the @ line stops looking like magic.
Foundations · Python for data engineers · Silver · Functions and laziness, lesson 1 of 3
On this page
Read first: Functions, *args, **kwargs and closures (skip if you know it)
In plain words first
Think of a gift and its wrapping paper:
Your function: the gift
The decorator: the wrapping
To wrap a function you need one fact that surprises many beginners: in Python a function is a value, like a number or a list. You can give it a second name, and you can pass it to another function. Note there are no brackets after greet when it is passed: you hand over the function itself, not its result.
def greet(name): return f"hello {name}" say = greet # a second name for the same function print(say("Asha")) def call_twice(func, value): return [func(value), func(value)] print(call_twice(greet, "Ravi")) # greet itself is passed in
Output from a real run
hello Asha ['hello Ravi', 'hello Ravi']
Wrapping a function by hand
Now write a function that takes a function and returns a new function. The new function prints a line, then calls the original and hands back its answer:
def quote(km): return 20 + 8 * km def shout(func): def wrapper(km): print("calling", func.__name__) return func(km) return wrapper loud_quote = shout(quote) print(loud_quote(2)) print(quote(2)) # the original is unchanged
Output from a real run
calling quote 36 36
shout(quote) does not call quote. It builds wrapper, which remembers func (it is a closureclosure: An inner function that remembers the variables of the function it was created in, even after that outer function has returned. Learn more →, from the previous lesson), and returns it. Only when you call loud_quote(2) does the wrapper run, print its line and call the real quote.
Usually you want every call to quote to go through the wrapper, so you reuse the same name: quote = shout(quote). That line is so common that Python has a shortcut for it, the @ sign.
@ is that same line, written above the function
Writing @shout on the line above def quote(...) means exactly quote = shout(quote) right after the function is defined. Here is what Python does, step by step:
Step 1 · define
def quote(km) and creates the function, just as it would without @.The command
def quote(km): return 20 + 8 * km
Step 2 · hand it over
@shout line, Python immediately calls shout(quote).The command
shout(quote)
Step 3 · get a wrapper
shout builds wrapper, which remembers the original quote, and returns it.The command
return wrapperStep 4 · rename
quote now points to the wrapper. The original is still alive, kept inside the wrapper as func.The command
quote = shout(quote)
Step 5 · call
quote(2) runs the wrapper: it prints its line, calls the original, and returns 36.The command
quote(2) # prints, then returns 36
The wrapper above only accepts km. A real decorator should work on any function, whatever arguments it takes. Two parameters you met in the previous lesson do that: *args collects any positional values and **kwargs any named ones, and func(*args, **kwargs) passes them on unchanged. The example below also counts calls, so you can watch the wrapping happen.
def audit(func): def wrapper(*args, **kwargs): wrapper.calls += 1 print(f"before: call number {wrapper.calls} of {func.__name__}") fare = func(*args, **kwargs) print(f"after: {func.__name__} returned {fare}") return fare wrapper.calls = 0 # functions are objects, so they can carry a value return wrapper @audit # the same as writing quote = audit(quote) after the def def quote(km): return 20 + 8 * km quote(2) quote(5) print("quote was called", quote.calls, "times") print("the name quote now points to:", quote.__name__)
Output from a real run
before: call number 1 of quote after: quote returned 36 before: call number 2 of quote after: quote returned 60 quote was called 2 times the name quote now points to: wrapper
Two things to notice. wrapper.calls is stored on the function itself (functions are objects you can label), so each decorated function has its own counter. And the last line shows the catch: quote is now really wrapper, which functools.wraps fixes below.
Closure or decorator?
| Closure | Decorator | |
|---|---|---|
| What it is | An inner function that remembers variables from the function that made it | A function that takes a function and returns a replacement |
| What goes in | Any values: make_fee(20) | A function: audit(quote) |
| What comes out | A function that uses those values | A new function that wraps the original |
| In these lessons | make_fee(20) remembers base = 20 | @audit wraps quote and counts its calls |
| How they connect | The building block | Usually built from a closure: wrapper remembers func |
make_fee(20) from the previous lesson is a closure: it returns a function that remembers base = 20. audit(quote) is a decorator: it takes a function and returns a new one. The wrapper it returns is itself a closure, because it remembers func.functools.wraps keeps the identity
As the last example showed, the decorated function is now called wrapper, and its docstring is gone too. Logs, error messages, documentation tools and frameworks that register functions by name all see the wrong thing. @functools.wraps(func) copies the name, docstring, module and more, and sets __wrapped__ to the original.
import functools def plain(func): def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper def careful(func): @functools.wraps(func) # copy func's name and docstring onto wrapper def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper @plain def eta_plain(km): "Minutes to deliver." return 10 + 3 * km @careful def eta_careful(km): "Minutes to deliver." return 10 + 3 * km print("without wraps:", eta_plain.__name__, "|", eta_plain.__doc__) print("with wraps: ", eta_careful.__name__, "|", eta_careful.__doc__)
Output from a real run
without wraps: wrapper | None with wraps: eta_careful | Minutes to deliver.
Decorators with settings
Sometimes the wrapping needs a setting: "allow at most 2 calls", "retry 3 times". You then write the decorator with brackets, @at_most(2). The rule from before still holds, with one extra step in front:
- 1Python first calls
at_most(2). It does not get the function yet, only the setting. - 2That call returns an ordinary decorator, which remembers
n = 2. - 3Python hands your function to that decorator, exactly like
@shout:send_sms = decorate(send_sms).
So a decorator with settings is three nested functions (layers 1 to 3 in the code): the outer takes the setting (n), the middle takes the function, the inner runs on every call. Check the setting in the outer layer, so at_most(0) fails when the file loads, not on the first call.
import functools def at_most(n): # layer 1: takes the setting if n < 1: raise ValueError("n must be at least 1") def decorate(func): # layer 2: takes the function @functools.wraps(func) def wrapper(*args, **kwargs): # layer 3: runs on every call if wrapper.used >= n: raise RuntimeError(f"{func.__name__} already ran {n} times") wrapper.used += 1 return func(*args, **kwargs) wrapper.used = 0 return wrapper return decorate # at_most(2) runs first and returns decorate, # then Python runs send_sms = decorate(send_sms) @at_most(2) def send_sms(text): return f"sent: {text}" print(send_sms("on the way")) print(send_sms("arrived")) try: send_sms("again") except RuntimeError as e: print("third call:", e)
Output from a real run
sent: on the way sent: arrived third call: send_sms already ran 2 times
What data engineers decorate
- Timing and logging: record how long each step took, with
time.perf_counter()and atry/finallyso failures are timed too. - Retries: call a flaky API again on listed exceptionsexception: An error raised while the program runs, like KeyError or ValueError. try/except catches it; otherwise the program stops with a traceback. Learn more →, waiting longer each time.
- Caching:
functools.lru_cacheorfunctools.cachememoise pure functions. - Registration: Airflow's
@taskand@dag, and pytest fixtures, are decorators that register functions.
functools.lru_cache(maxsize=...): it handles keyword argumentskeyword argument: An argument passed by name, like round(x, ndigits=2), so the order does not matter and the call reads clearly. Learn more →, has a size limit and reports hits and misses with cache_info().A template to start every decorator from. Fill in the two comments and you are done:
import functools def my_decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): # 1. do something before the call value = func(*args, **kwargs) # 2. do something after the call return value return wrapper @my_decorator def add_tip(amount): return amount + 20 print(add_tip(100), add_tip.__name__)
Output from a real run
120 add_tip
Common mistakes
- Forgetting to return the wrapper, or the result — Without
return wrapperthe name becomes None; withoutreturn resultevery call returns None. - Forgetting functools.wraps — The function loses its name and docstring. Always wrap.
- Writing @decorator() for a decorator that takes no arguments — That calls the decorator with no function. Match the layers to the usage.
- Swallowing exceptions in a wrapper — Callers think the call succeeded. Re-raise after logging.
Key takeaways
- A function is a value: you can pass it to another function.
- A decorator takes a function and returns a wrapper that adds something around it.
- @dec above def f means f = dec(f).
- Wrappers take *args, **kwargs and return the result.
- functools.wraps keeps the name, docstring and __wrapped__.
- With settings: factory → decorator → wrapper.
Interview prep
THE QUESTION
"Write a decorator that logs how long a function takes."
Avoid: "a decorator is a special Python feature for adding behaviour". It is plain function application: @d above def f is f = d(f).
Follow-ups · answer out loud, then open
Follow-up"How do you write a decorator that takes arguments?"
Scenario"Add retries with exponential backoff to every call our pipeline makes to a flaky API."
Trap"Stacked decorators run from top to bottom when the function is defined."
Check yourself
4 questionsWhat does shout(quote) do (no @ involved)?
Show the answer
Returns a new function that wraps quote. It builds and returns the wrapper; quote only runs when the wrapper is called.
@cache above def f is the same as...
Show the answer
f = cache(f). The decorator receives the function and its result replaces it.
What does functools.wraps fix?
Show the answer
The wrapper hides the original name and docstring. It copies the metadata onto the wrapper.
@retry(3) works because retry(3) returns...
Show the answer
A decorator. The call happens first; its result decorates.
Practise this
Problems that use this, graded on hidden tests
- A Logging Decorator That Keeps MetadataFunctions & decorators Easy
- Memoize a FunctionFunctions & decorators Medium
- Time Every CallFunctions & decorators Medium
Keep going
Up next · Functions and laziness · lesson 2 of 3 · 6 min readGenerators and lazy evaluation
yield, constant-memory pipelines, endless inputs and the one-pass rule.
Related lessons
Functions, *args, **kwargs and closuresPython for data engineers · 5 min read
Exceptions and context managers
Previous: Functions, *args, **kwargs and closures
Primary sources: functools · Function definitions and decorators