Skip to content
Tutorials Center
My learning

Topics

Lesson 45 of 149 ยท Functions

Decorators

Learn how Python decorators wrap functions to add timing, logging, caching or validation, why functools.wraps matters, and how to write decorators that take arguments.

A decorator is a function that takes another function and returns a modified version of it. You apply one by writing @name on the line above a def. Decorators let you add behavior such as logging, timing, caching, access checks or retries to many functions without touching their bodies.

You've already used one: @cache in Recursion. In this lesson you'll see that decorators aren't magic at all. They're a short syntax for something you can already do with higher-order functions and closures. Then you'll write your own, keep their metadata intact with functools.wraps, and build decorators that accept arguments.

A decorator is a function that returns a function

Start without any special syntax. Here's a function that takes a function, wraps it in a new one that prints a message before and after the call, and returns the wrapper:

Python Wrapping by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The line make_tea = announce(make_tea) is the whole idea. The name make_tea now refers to wrapper, which is a closure that remembers the original function as func.

The @ syntax

Writing @announce above a def does exactly the same thing as that reassignment, but it puts the decoration where readers will see it, right at the definition:

Python
@announce
def make_tea():
    print("  Boiling water and steeping leaves")

# is equivalent to:
# def make_tea(): ...
# make_tea = announce(make_tea)

The decorator runs once, when the function is defined. The wrapper runs every time the decorated function is called.

Handling arguments and return values

The wrapper above only works for functions with no parameters, and it throws away the return value. A general-purpose decorator should accept any arguments with *args and **kwargs (see Arguments), pass them through, and return whatever the original function returns:

Python A timing decorator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The pattern def wrapper(*args, **kwargs) + return func(*args, **kwargs) is the skeleton of almost every decorator you'll write.

Keep metadata with functools.wraps

There's a hidden problem with the decorators so far. After decoration, the name refers to wrapper, so the function's name, docstring and other metadata now describe the wrapper instead of the original:

Python functools.wraps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

functools.wraps(func) is itself a decorator. It copies __name__, __doc__, __module__, __qualname__, type annotations and more from func onto wrapper. Without it, tracebacks, help(), logging and testing tools all report the wrong function. Always use @functools.wraps in your decorators.

Practical decorators

Decorators are best for "cross-cutting" concerns: behavior that many unrelated functions need, but that has nothing to do with what any single function is for. Here are two common examples.

Python Logging and validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Stacking decorators

When you stack decorators, they're applied bottom-up: the one closest to the def wraps the function first. In the example, bmi = log_calls(positive_numbers(bmi)). At call time, the outer wrapper runs first, so log_calls sees every call, including the one that positive_numbers rejects. Swap the order and the log would show only calls that pass validation. Order matters, so think about which behavior should see what.

Decorators with arguments

What if you want @retry(times=3) or @repeat(2)? Now the thing after @ is a call that must return a decorator. That means three levels of functions:

  1. The outer function takes the decorator's arguments and returns a decorator.
  2. The decorator takes the function and returns a wrapper.
  3. The wrapper runs on every call.
Python A decorator with arguments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Reading @retry(times=5, exceptions=(ConnectionError,)) from left to right: Python first calls retry(...), which returns decorator; then it applies decorator to flaky_download. Note that even with no arguments you must write @retry() with parentheses, because retry itself isn't a decorator, it's a decorator factory.

Tip: Catch only the exceptions you expect to be temporary, like ConnectionError. A retry decorator that catches everything would also retry real bugs such as a TypeError, hiding them behind repeated attempts.

Decorators that register functions

A decorator doesn't have to wrap anything. It can simply record the function somewhere and return it unchanged. This is how many frameworks map commands, events or URLs to handler functions:

Python
commands = {}

def command(name):
    def decorator(func):
        commands[name] = func
        return func          # the original, unchanged
    return decorator

@command("greet")
def greet(who):
    return f"Hello, {who}!"

print(commands["greet"]("Mia"))   # Hello, Mia!

Because the function is returned as is, it needs no wrapper and no functools.wraps. The decorator's only job is the side effect of registering it.

Decorators in the standard library

You'll meet many decorators that ship with Python. A few you'll use often:

  • @functools.cache and @functools.lru_cache(maxsize=...) memoize results (Recursion).
  • @property, @classmethod and @staticmethod change how methods behave in classes (Properties, Instance, Class and Static Methods).
  • @dataclass generates __init__, __repr__ and comparisons for a class (Data Classes). Yes, decorators work on classes too.
  • @contextlib.contextmanager turns a generator into a context manager (Context Managers).

Web frameworks use them heavily as well, for example to connect a URL to a function with something like @app.route("/about").

When to use a decorator

Decorators are a great fit when the added behavior is the same for many functions and independent of their purpose: timing, logging, caching, permission checks, registering a function in a list, or retrying. They're a poor fit for logic specific to one function; just put that code in the function. And because the wrapping is invisible at the call site, keep decorators predictable: pass arguments through, return the result, and use functools.wraps.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is @timed above def work(): ... equivalent to?

    The decorator receives the function and the name is rebound to whatever it returns.
  2. 2. Why should a wrapper accept *args, **kwargs?

    A general decorator doesn't know the decorated function's parameters, so it accepts and forwards everything.
  3. 3. What does functools.wraps(func) do?

    Without it, the decorated function reports the wrapper's name and loses its docstring.
  4. 4. Given @a on the first line and @b on the second, directly above def f, what is f?

    Decorators are applied bottom-up, so b wraps f first and a wraps the result.
  5. 5. How many levels of nested functions does a decorator that takes its own arguments, like @retry(times=3), usually have?

    A factory that takes the arguments, a decorator that takes the function, and the wrapper that runs on each call.

Summary

  • A decorator takes a function and returns a replacement; @deco above def f means f = deco(f).
  • The decorator runs once at definition time; the wrapper runs on every call.
  • Write wrappers as def wrapper(*args, **kwargs), forward the arguments, and return the original result.
  • Always apply @functools.wraps(func) to the wrapper to keep the name, docstring and annotations.
  • Stacked decorators apply bottom-up; the top one runs first at call time.
  • Decorators with arguments need a third layer: a factory that returns the decorator. Use parentheses even with no arguments.
  • Good uses: logging, timing, caching, validation, retries, registration. Python itself provides @cache, @property, @dataclass and more.

Next: Generators, functions that produce values one at a time with yield.