Back to Explore
GuideVibeFix editorialUpdated Nov 22, 2026

Wrap a function: Python decorators

A decorator is a function that takes a function and returns one. Following Tutorial Chapter 4 and Language Reference section 8.7: the @ shorthand, evaluation at definition time, writing wrappers, functools.wraps, decorators with arguments, and stacking order — plus a 100-mistake breakdown from a fictional bookstore script.

Real photo: close-up of Python code on a monitor, a dark editor showing @classmethod on line 41, syntax highlighting in colour

First, the boundaries of this guide. This is the seventh article in the "Python basics" series, continuing from the first six: the first covered variables, types, and control flow; the second, functions and modules; the third, classes and inheritance; the fourth, exception handling; the fifth, file I/O; the sixth, comprehensions and generators. This one covers decorators: wrapping a function in an extra layer so you can add timing, logging, or retries without changing the function itself. The "Morning Light Bookstore" used below is the same fictional practice project as before: a small street bookstore whose bookkeeping script can already count stock, apply discounts, manage books with classes, catch errors, save its ledger to files, and pick books with comprehensions. The new problem here is that the bookkeeping functions all need timing and logging, and copying the timing code into every function is tedious — a decorator lets you write that repeated work once. Everything said here about decorators comes from the official Python Tutorial, Chapter 4, "More Control Flow Tools", sections 4.8 and 4.9 (functions as objects, *args and **kwargs), the Language Reference, Chapter 8, section 8.7, "Function definitions" (how decorator expressions are evaluated), and the functools library documentation (functools.wraps); see each article's meta information and evidence record for the sources. All operations, code, and numbers using the Morning Light Bookstore are invented to explain the technique and are not real records. By the end of this guide, you should be able to do five things: explain what a decorator is — a function that takes a function and returns a function; write a general-purpose wrapper with *args and **kwargs; use functools.wraps to keep the original function's name and docstring; write a decorator that takes arguments (three layers of nesting); and stack several decorators, explaining that they apply bottom-up. The boundary with the second guide is this: that guide covered how to define functions, pass arguments, and return values; this one does not repeat that, and only covers how a function can itself be passed around, wrapped, and returned. The boundary with the third guide is this: that guide used @property, @staticmethod, and @classmethod but only said "write it this way"; this guide explains what the @ is actually doing.

Step 1: Functions are objects — the ground decorators stand on

Decorators only work because in Python a function is itself an object. The official Tutorial, section 4.8, puts it plainly: a function definition associates the function name with a function object, and other names can also point to that same function object and be used to call it. The official example assigns fib to f and then calls f(100):

>>> fib
<function fib at 10042ed0>
>>> f = fib
>>> f(100)
0 1 1 2 3 5 8 13 21 34 55 89

If a function can be assigned to a variable, it can be passed as an argument to another function and returned as a result. A decorator uses exactly that: it is a function that takes in a function and returns a new one — usually a version wrapped with some extra work. The bookstore version: a greeting function, assigned to another name, still works:

def greet(name):
    return f"Hello, {name}"

say = greet
say("Lee")  # 'Hello, Lee'
greet.__name__  # 'greet'

say("Lee") gives 'Hello, Lee', and greet.__name__ is 'greet'. This step uses no decorator syntax at all, but it is the ground everything else stands on: if you accept that functions can be passed around like numbers and strings, a decorator is only one thin layer away. One more piece of ground is worth stating on its own: the programmer's note in Language Reference section 8.7 says functions are first-class objects, a def executed inside a function defines a local function that can be returned or passed around, and free variables used in the nested function can access the locals of the enclosing function. A decorator's wrapper is exactly such a nested function:

def make_adder(n):
    def add(x):
        return x + n
    return add

add5 = make_adder(5)
add5(3)  # 8, the inner function remembers that n is 5

add5(3) gives 8, because the inner function add remembers that the outer make_adder's local variable n is 5. A decorator's wrapper works the same way: it is defined inside the outer function, remembers the original function the outer function received, and runs it when called. My judgement is this: before learning decorators, run the sentence "functions are objects" through your head three times — every time decorators feel confusing later, it is because you forgot that.

Step 2: @ is shorthand — a decorator runs when the function is defined

Language Reference section 8.7 states what @ means, plainly: a function definition may be wrapped by one or more decorator expressions; decorator expressions are evaluated when the function is defined; the result must be a callable, which is invoked with the function object as its only argument; and the returned value is bound to the function name instead of the function object. Multiple decorators are applied in nested fashion, as in the official example:

@f1(arg)
@f2
def func(): pass

which is roughly equivalent to:

def func(): pass
func = f1(arg)(f2(func))

except that the original function is not temporarily bound to the name func. Note two key points. First, a decorator runs when the function is defined, not when the function is called — importing a module runs the decorators inside it once. Second, writing @timer above a def is the same thing as writing the function and then total = timer(total); the @ just makes the writing shorter and the intent clearer. The bookstore version: a decorator that records function names runs at definition time, before the function is ever called:

calls = []

def register(func):
    calls.append(func.__name__)
    return func

@register
def sell():
    pass

calls  # ['sell']; sell was never called, yet its name is already recorded

My judgement is this: the easiest thing to misunderstand about decorators is when they run — remember that a decorator runs the moment the def executes, and what runs when you call the function is the wrapper the decorator returned; do not mix those two up. One more note on how much freedom the syntax allows: Language Reference section 8.7 notes that since Python 3.9, a decorator can be any valid assignment expression, not just a single name — a decorator taken from a dictionary, or a method of some object, can sit directly after the @; before 3.9 the grammar was much more restrictive, as described in PEP 614. In everyday code a single name is the most common case, but knowing this rule means you will not be surprised when you see something dotted or subscripted after the @ in someone else's code: after the @ is just an expression, evaluated first and then called, no different from any other expression.

Step 3: Write your first decorator — a timer, with *args and **kwargs

The first genuinely useful decorator is a timer: wrap a function, record the time before it runs and after it finishes, and the difference is how long it took. The wrapper has to accept every argument the original function accepts, so its signature is written as (*args, **kwargs) — Tutorial section 4.9 explains that *name receives extra positional arguments as a tuple and **name receives extra keyword arguments as a dictionary; the wrapper passes both through unchanged to the original function, so it can wrap anything. The bookstore version: add timing to the function that totals stock value:

import time

def timer(func):
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        elapsed = time.perf_counter() - start
        print(f"{func.__name__} took {elapsed:.4f}s")
        return result
    return wrapper

books = [('The Three-Body Problem', 59.0, 7), ('Twenty Thousand Leagues Under the Seas', 39.5, 12), ('To Live', 29.0, 5)]

def stock_value(books):
    return sum(price * stock for _, price, stock in books)

stock_value(books)  # 1032.0
timed = timer(stock_value)
timed(books)  # prints one timing line, then returns 1032.0

The three books' stock values are 413.0, 474.0, and 145.0, totalling 1032.0 — the same result as the hand calculation, the file calculation, and the comprehension calculation in earlier guides. Writing timed = timer(stock_value) by hand is exactly equivalent to the @ form:

@timer
def total(books):
    return sum(price * stock for _, price, stock in books)

total(books)  # prints the timing, returns 1032.0

By the way, here is the simplest decorator of all: one that does nothing and returns the function unchanged. It is not written to be used, but to confirm the rule that "whatever a decorator returns is what the name gets bound to":

def noop(func):
    return func

@noop
def double(x):
    return x * 2

double(21)  # 42
double.__name__  # 'double'; the returned function keeps its name

My judgement is this: the fixed pattern for writing a decorator is only three lines — the outer function takes the function, the inner wrapper takes the arguments, and you return the wrapper; memorise that pattern first, and only then think about the specific extra work, whether timing, logging, or retrying.

Step 4: The wrapper must hand the return value back

The most common beginner mistake with decorators is a wrapper that calls the original function but forgets to return the result. The caller gets None, and the failure is silent — the function body definitely ran, but its return value was thrown away. The bookstore version: a decorator that forgets to return:

def broken(func):
    def wrapper(*args, **kwargs):
        func(*args, **kwargs)  # called, but not returned
    return wrapper

@broken
def add(a, b):
    return a + b

add(2, 3)  # None, not 5

add(2, 3) gives None, because the wrapper never handed back the result of func(*args, **kwargs). The fix is a single line: return func(*args, **kwargs). Keep this rule next to the timer from step 3: the timer first catches the result with result = func(*args, **kwargs), prints the elapsed time, and then does return result — both steps are required. My judgement is this: after writing a decorator, ask yourself one question first — "where did the original function's return value go?" — and do not move on until you can answer it.

Step 5: The name got covered up — functools.wraps

Decorators have another, quieter side effect: after decorating, the function's name and docstring become the wrapper's. The total from step 3, once decorated, has total.__name__ equal to 'wrapper', not 'total' — because the name total is now bound to the wrapper function. That fake name will mislead you when you read a traceback or look up documentation. The standard library's answer is functools.wraps: add one more decorator on top of the wrapper, and it copies the original function's __name__, __doc__, and similar information onto the wrapper. The bookstore version:

from functools import wraps

def logged(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper

@logged
def sell_book(title):
    """Sell one book."""
    return title

sell_book.__name__  # 'sell_book', not 'wrapper'
sell_book.__doc__  # 'Sell one book.'
sell_book("The Three-Body Problem")  # 'The Three-Body Problem'

Without @wraps(func), __name__ would be 'wrapper' and __doc__ would be None; with it, the name and docstring are the same as before. My judgement is this: there is no exception to @wraps(func) — add it whenever you write a wrapper; it is a single line, and the trouble it saves is larger than you would expect.

Step 6: A decorator with arguments — one more layer of nesting

Sometimes the decorator itself wants an argument, such as the 3 in "retry 3 times". The way to do it is one more layer: the outermost function takes the decorator's argument and returns the real decorator; the real decorator takes the function and returns the wrapper; the wrapper takes the call's arguments. Each of the three layers has its own job — do not miscount them. The bookstore version: the supplier's API occasionally fails, so retry three times before giving up:

def retry(times):
    def decorator(func):
        def wrapper(*args, **kwargs):
            last = None
            for _ in range(times):
                try:
                    return func(*args, **kwargs)
                except ValueError as e:
                    last = e
            raise last
        return wrapper
    return decorator

attempts = {"n": 0}

@retry(times=3)
def flaky():
    attempts["n"] += 1
    if attempts["n"] < 3:
        raise ValueError("not yet")
    return "ok"

flaky()  # 'ok', succeeding only on the third try
attempts["n"]  # 3, three attempts in total

flaky raises ValueError on the first two tries and returns 'ok' on the third; attempts["n"] is 3, meaning three attempts happened. Note the parentheses in @retry(times=3): it first calls retry(times=3) to get a decorator, and then uses that decorator on flaky. Written as @retry without parentheses, retry's first argument would be the function itself, and the meaning would be completely different. Two more points worth noting in passing: first, the wrapper inside retry can also take @wraps(func) — the rule from step 5 applies inside three layers of nesting just the same; second, catching only ValueError above is deliberately narrow — retrying should be reserved for errors you know will clear up on their own, because retrying every kind of error also retries genuine bugs three times before reporting them, which makes debugging harder. My judgement is this: when you see parentheses after a decorator, count the layers first — a decorator with arguments always has three, and one layer short means it will not run at all.

Step 7: Stacking decorators — they run bottom-up

Several decorators can be stacked on one function. Language Reference section 8.7 already states the order: with @f1(arg) on top and @f2 below, the equivalent is func = f1(arg)(f2(func)) — the lower decorator wraps first, then the upper one wraps that; when the function is called, the topmost wrapper runs first. The bookstore version: tag a book name with B first, then A:

def add_tag(tag):
    def decorator(func):
        def wrapper(*args, **kwargs):
            return f"[{tag}] " + func(*args, **kwargs)
        return wrapper
    return decorator

@add_tag("A")
@add_tag("B")
def book_name():
    return "book"

book_name()  # '[A] [B] book'

book_name() gives '[A] [B] book': B is attached first, A is attached outside it; at call time A's wrapper runs first, calls B's wrapper, and only then the original function. Write them in the opposite order and the result becomes '[B] [A] book'. The order also has real consequences for timing and logging: with @timer on top and @logged below, the timed span includes the logging; the other way around, it does not. My judgement is this: when stacking decorators, read from the bottom up once — "who wraps whom first" — and then think about who runs first at call time; writing the order backwards raises no error, it just silently produces a different result.

Step 8: Decorators you have already used — @property and class decorators

Decorators are nothing new; the third guide already used them: @property turns a method into a value read like an attribute, @staticmethod makes a method that does not receive self, and @classmethod makes a method that receives the class itself instead of an instance. They are all decorators — each takes in a function and returns a reworked object. The bookstore version: bring back the Book class from the third guide and use all three built-in decorators at once:

class Book:
    def __init__(self, title, price, stock):
        self.title = title
        self.price = price
        self.stock = stock

    @property
    def value(self):
        return self.price * self.stock

    @staticmethod
    def discount(price, rate):
        return round(price * rate, 2)

    @classmethod
    def from_row(cls, row):
        return cls(row["title"], row["price"], row["stock"])

Book('The Three-Body Problem', 59.0, 7).value  # 413.0
Book.discount(59.0, 0.9)  # 53.1
Book.from_row({"title": "To Live", "price": 29.0, "stock": 5}).value  # 145.0

The stock value of The Three-Body Problem is 413.0 (59.0 times 7), its 10%-off price is 53.1, and the stock value of To Live is 145.0 (29.0 times 5). Decorators can decorate classes too, not just functions: Language Reference section 8.8 says the evaluation rules for class decorators are the same as for function decorators, and the result is bound to the class name. The bookstore version: count how many shelf instances were created:

def counted(cls):
    cls.instances = 0
    orig_init = cls.__init__
    def new_init(self, *a, **k):
        orig_init(self, *a, **k)
        cls.instances += 1
    cls.__init__ = new_init
    return cls

@counted
class Shelf:
    pass

Shelf()
Shelf()
Shelf.instances  # 2

Two Shelf instances were created, and Shelf.instances is 2. My judgement is this: with the built-in decorators, being able to use them is enough for now — there is no need to take apart how they work inside; knowing that "whatever follows the @ is a callable, and decorating is one function call" is enough to connect this guide with the third one.

Step 9: Three pitfalls — timing, signatures, and return types

The first pitfall is timing: a decorator runs at definition time, and the wrapper runs at call time. Step 2's register already proved it — the name was recorded before the function was ever called. The practical consequence is that heavy work inside a decorator (connecting to a database, reading a file) runs when the module is imported, so do not put that kind of work in a decorator. The second pitfall is the signature: the wrapper must be written as (*args, **kwargs) and pass them through unchanged; written with fixed parameters, it raises TypeError as soon as it meets a call style it cannot accept. The third pitfall is the return type: Language Reference section 8.7 says the result of evaluating a decorator expression must be a callable, and the returned value is bound to the function name — if a decorator returns something that is not a function (say, the integer 42), defining it raises no error, and the error only appears when you call it: TypeError: 'int' object is not callable. The bookstore version:

def bad(func):
    return 42

@bad
def price():
    return 59.0

price()  # TypeError: 'int' object is not callable

Defining price raised no error; calling price() did, because the name is bound to the integer 42. Methods can be decorated too, with no change in how you write it: when a method is called, its first argument is the instance self, which flows into the wrapper through *args and is passed on unchanged to the original method:

class Counter:
    def __init__(self):
        self.n = 0

    @timer
    def bump(self):
        self.n += 1
        return self.n

c = Counter()
c.bump()  # prints the timing, returns 1
c.bump()  # prints the timing, returns 2

My judgement is this: when a decorator misbehaves, check three places first — what ran at definition time, whether the wrapper accepted every argument, and what the decorator actually returned; checking those three will locate the problem nine times out of ten.

Step 10: Wrap-up — a decorator is "wrap it and hand it back", plus a chart of mistakes

Finally, connect this guide with the earlier ones: the functions from the second guide are the ground floor, and decorators are the second floor built on top — because a function can be passed around as an object, a decorator takes a function, wraps it, and hands it back; the generator functions from the sixth guide can be decorated too, with the same yield pattern inside the wrapper; and the @property, @staticmethod, and @classmethod from the third guide now have a single shared explanation — they are decorators. One complete example: give the bookkeeping function logging and timing at the same time:

from functools import wraps

def logged(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        print(f"calling {func.__name__}")
        return func(*args, **kwargs)
    return wrapper

@logged
@timer
def total(books):
    return sum(price * stock for _, price, stock in books)

total(books)  # prints 'calling total' first, then the timing, returns 1032.0

Calling total(books) prints calling total first, then the timing, and returns 1032.0; with @logged on top and @timer below, the logging wrapper runs first and the timing wrapper second. Try it yourself: write your own decorator for the bookstore's discount function — it should print "discount started" when called, return the discounted price, and leave the function with its original name after decorating. Check your work against three points: does the wrapper take (*args, **kwargs); did the original function's return value get returned; and is there a @wraps(func) on the wrapper? Once all three are right, think about whether the decorator runs at definition time or at call time — if you put a print inside the decorator, will it sound off when the module is imported? Once you can do that exercise, the pattern in this guide is genuinely yours: whether the job is timing, logging, or retrying, it is the same pattern with different work filled in.

Finally, the chart of mistakes for this guide. Example: the fictional Morning Light Bookstore bookkeeping script, in its seventh month of learning Python, made 100 decorator-related mistakes, distributed as follows. The most common mistake, at the top of the chart, is forgetting to return the original function's result from the wrapper.

100 decorator mistakes in the seventh month of learning Python: forgot to return the original function's result from the wrapper 26, wrapper without *args and **kwargs could not accept the arguments 18, no @wraps so the function name and docstring were covered up 16, thought the decorator runs at call time when it actually runs at definition time 12, decorator with arguments missing one layer of nesting 12, several decorators stacked in the wrong order 9, changed the function signature inside the decorator so callers broke 7

Looking back over the ten steps, this guide really only taught three things. First, a decorator is one function call: the @ is shorthand, the decorator expression is evaluated at definition time, and what it returns is bound to the function name; several decorators wrap bottom-up and run top-down when called. Second, the pattern for writing a decorator is fixed: the outer layer takes the function, the inner wrapper takes *args and **kwargs, hands the return value back, and adds @wraps to keep the name and docstring; a decorator with arguments adds one more layer. Third, the built-in @property, @staticmethod, and @classmethod, along with class decorators, are all the same thing — do not treat them as a different kind of syntax. The next guide covers the match statement: the shop's paperwork comes in several shapes — sales, restocking, returns — and writing them out with if and elif gets long and easy to get wrong, while match dispatches by shape, so you can see at a glance which road each kind of paperwork takes.

Views 0Comments 0

Comments (0)

ME
0/1000
Loading comments...

Sources

Browse projectsPublish your project

Related articles