Skip to content
Silver 8 min read · Functions 3 practice problems ↓

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

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

It does the real work, such as working out a delivery fare. You do not change it.

The decorator: the wrapping

It goes around the gift and adds something on the outside: a log line before each call, a timer, a retry. The gift inside is the same.

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.

Python · a function is a value
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:

Python · a wrapper, built without @
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

Python reads 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

Because of the @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 wrapper

Step 4 · rename

The name 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

Every later 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.

Python · a decorator that counts calls and shows what it wraps
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?

ClosureDecorator
What it isAn inner function that remembers variables from the function that made itA function that takes a function and returns a replacement
What goes inAny values: make_fee(20)A function: audit(quote)
What comes outA function that uses those valuesA new function that wraps the original
In these lessonsmake_fee(20) remembers base = 20@audit wraps quote and counts its calls
How they connectThe building blockUsually built from a closure: wrapper remembers func
Every decorator here is a closure, but not every closure is a decorator: 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.

Python · with and without wraps
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:

  1. 1
    Python first calls at_most(2). It does not get the function yet, only the setting.
  2. 2
    That call returns an ordinary decorator, which remembers n = 2.
  3. 3
    Python 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.

Python · a decorator factory: allow at most n calls
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 a try/finally so 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_cache or functools.cache memoise pure functions.
  • Registration: Airflow's @task and @dag, and pytest fixtures, are decorators that register functions.
Tip: For caching, prefer the standard 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:

Python · the shape of every decorator
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 wrapper the name becomes None; without return result every 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."

A wrapper that reads time.perf_counter() before the call and again in a finally block, so failed calls are timed too, then logs the difference and returns or re-raises. I decorate the wrapper with functools.wraps so the logged name is the real function name. If it needed settings like a log level, I would make it a factory: log_time(level) returns the decorator.

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?"
One more layer: a factory that takes the arguments and returns the actual decorator, which takes the function and returns the wrapper. @retry(3) calls retry(3) first; its result decorates.
Scenario"Add retries with exponential backoff to every call our pipeline makes to a flaky API."
A retry(attempts, exceptions, delay, backoff) decorator factory: the wrapper loops over attempts, catches only the transient exception types, sleeps delay and multiplies it by backoff, and re-raises after the last attempt. Add jitter so many workers do not retry in lockstep, and keep functools.wraps for readable logs.
Trap"Stacked decorators run from top to bottom when the function is defined."
They are applied bottom-up: the one nearest the def wraps first. At call time the outermost (top) wrapper runs first.

Check yourself

4 questions

What 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

See all 5 problems →

Keep going

Up next · Functions and laziness · lesson 2 of 3 · 6 min read
Generators and lazy evaluation
yield, constant-memory pipelines, endless inputs and the one-pass rule.

Related lessons

Previous: Functions, *args, **kwargs and closures

Primary sources: functools · Function definitions and decorators