Advanced   Chapter 139 · 35 min read · Module 11: Advanced Python

Decorators

Learning objectives
  • After this chapter you can explain that a decorator takes a function and returns a new function.
  • You can write a simple decorator and apply it with the @ symbol.
  • You can make a decorator work with any arguments using *args and **kwargs.
  • You can write a decorator that takes its own arguments.
  • You can use functools.wraps to keep the name and docstring of the original function.

Sometimes you want to add the same extra step to many functions, such as printing a message, timing the work, or checking a rule. Copying that code into every function is tiring and easy to get wrong. A decorator lets you write the extra step once and attach it to any function.

A decorator is a function that receives another function, wraps it with new behaviour, and returns the wrapped version. Python gives a neat shortcut for this: you write the decorator name with an @ sign on the line above the function.

In this chapter you will build decorators step by step. You will start with the idea that functions are ordinary values, then write simple decorators, handle arguments, create decorators that take settings, and learn a standard tool called functools.wraps.

Functions are values

In Python a function is an object, just like a number or a string. You can store it in a variable, pass it to another function, and return it from a function. Decorators depend completely on this idea. If a function can be given to another function, then another function can wrap it.

Decorator: a function that takes a function, adds behaviour around it, and returns a new function
Example 1: Passing a function around
def shout(text):
    return text.upper() + "!"

def apply(func, value):
    return func(value)

print(apply(shout, "hello"))
say = shout
print(say("hi"))
HELLO! HI!

Your first decorator

Inside the decorator we define a small inner function, usually called wrapper. The wrapper runs extra code and also calls the original function. The decorator returns the wrapper. After decoration, the original name points to the wrapper, so every call goes through the extra step.

Example 2: A logging decorator
def log_call(func):
    def wrapper():
        print("before")
        func()
        print("after")
    return wrapper

@log_call
def greet():
    print("hello")

greet()
before hello after

The line @log_call above greet is a short way of writing greet = log_call(greet). Both forms do the same thing. The decorator runs once, when the function is defined, and the wrapper runs every time you call the function.

Handling arguments and return values

Real functions take arguments and return results. A wrapper must pass them along. Use *args and **kwargs so the wrapper accepts any call, and return the result of the original function. If you forget the return, the decorated function will give back None.

Example 3: A flexible decorator
def double_result(func):
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        return result * 2
    return wrapper

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

print(add(2, 3))
print(add(a=10, b=1))
10 22

Keeping the original details with functools.wraps

A plain wrapper hides the real function. Its name becomes wrapper and its docstring is lost, which confuses debugging tools and help(). The standard fix is to decorate the wrapper with functools.wraps(func). It copies the name, docstring and other details from the original function onto the wrapper.

Example 4: Using functools.wraps
import functools

def plain(func):
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper

def careful(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper

@plain
def a():
    "Doc A"

@careful
def b():
    "Doc B"

print(a.__name__, a.__doc__)
print(b.__name__, b.__doc__)
wrapper None b Doc B

Decorators that take arguments

Sometimes the decorator itself needs a setting, such as how many times to repeat a call. For that you add one more layer. The outer function takes the setting and returns the real decorator. Then @repeat(3) first calls repeat(3), and the result is used as the decorator.

Example 5: A decorator with a setting
import functools

def repeat(times):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            result = None
            for _ in range(times):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator

@repeat(3)
def say(word):
    print(word)

say("hey")
hey hey hey
You can stack decorators. The one closest to the function is applied first, and the top one wraps the result.

Thinking about order and design

When two decorators are stacked, read them from the bottom up. The decorator nearest to the def line receives the plain function first. The next one up receives the already wrapped result. When you call the function, control travels the opposite way, from the outermost wrapper inward until the original code runs. Keeping this picture in mind makes stacked decorators easy to predict.

Good decorators are small and focused. One decorator should add one idea, such as logging or checking input. If you need several ideas, stack several decorators instead of building one giant wrapper. Also remember that a decorator adds a small cost to every call, so avoid heavy work inside the wrapper unless it is really needed.

Common uses

Decorators are everywhere in Python. They are used for timing code, caching results, checking permissions, registering web routes, and retrying failed work. The standard library offers ready-made ones such as functools.lru_cache, staticmethod and property. Once you understand the wrapper pattern, you can read most of them easily.

Python syntax

Syntax
def decorator(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper
Syntax
@decorator
def name():
    ...
Syntax
def with_setting(value):
    def decorator(func):
        ...
        return wrapper
    return decorator

Real-world applications

  • Timing how long a function takes
  • Caching results of slow calculations
  • Checking that a user is logged in before running a function
  • Logging every call to a function
  • Registering functions as handlers in a web framework

Common mistakes

Mistake: Forgetting to return the wrapper from the decorator
Fix: The last line of the decorator must be return wrapper, otherwise the decorated name becomes None.
Mistake: Not returning the result of the original function inside the wrapper
Fix: Write return func(*args, **kwargs) so callers receive the value.
Mistake: Writing a wrapper that accepts no arguments for a function that needs them
Fix: Use def wrapper(*args, **kwargs) and pass them on.
Mistake: Writing @repeat instead of @repeat(3) for a decorator that takes arguments
Fix: Call the outer function with its settings so it returns the real decorator.
Mistake: Losing the function name and docstring
Fix: Add @functools.wraps(func) above the wrapper.

Important tips

  • Always use functools.wraps in decorators you publish.
  • Keep the wrapper small and put heavy logic in helper functions.
  • Test the plain function first, then add the decorator.
  • Use *args and **kwargs unless you are sure about the signature.

Key points summary

  • A decorator takes a function and returns a function.
  • @name above a def means func = name(func).
  • The wrapper should accept *args and **kwargs and return the result.
  • functools.wraps keeps the original name and docstring.
  • A decorator with arguments needs three nested functions.
  • Stacked decorators apply from the bottom up.

Exam and interview points

  • @d on def f is the same as f = d(f).
  • A decorator with arguments returns a decorator.
  • Without functools.wraps, __name__ becomes wrapper.
  • Multiple decorators are applied nearest-first.
  • Decorators run at definition time, wrappers at call time.

Quick revision

  • Decorator = function that wraps a function
  • @d means f = d(f)
  • Use *args and **kwargs in the wrapper
  • Return the result and return the wrapper
  • functools.wraps keeps metadata
  • Extra layer for decorator arguments

Frequently asked questions

When does the decorator code run?

The decorator function itself runs once, when the decorated function is defined. The wrapper runs on every call.

Can I use the same decorator on many functions?

Yes. That is the main benefit. Write it once and add the @ line to each function.

Can a class be a decorator?

Yes. Any callable that takes a function and returns a callable can be used. Classes with a __call__ method are sometimes used for this.

How do I see the original function behind a wrapped one?

If you used functools.wraps, the original is available as the __wrapped__ attribute.

Practise this chapter

18 practice questions Take the chapter quiz

Related chapters