How do I make function decorators and chain them together in Python?

Better Stack Team
Updated on January 26, 2023

In Python, a decorator is a design pattern to extend the functionality of a function without modifying its code. You can create a decorator function using the @decorator_function syntax, or by calling the decorator function and passing the decorated function as an argument. For example:

 
def my_decorator(func):
    def wrapper(*args, **kwargs):
        print("Before function call")
        result = func(*args, **kwargs)
        print("After function call")
        return result
    return wrapper

@my_decorator
def my_function():
    print("Inside function")

my_function()
# Output: "Before function call", "Inside function", "After function call"

You can chain decorators together by applying multiple decorators to a single function. The decorators will be applied in the order they are specified, with the innermost decorator being applied first. For example:

 
def decorator1(func):
    def wrapper(*args, **kwargs):
        print("Decorator 1")
        return func(*args, **kwargs)
    return wrapper

def decorator2(func):
    def wrapper(*args, **kwargs):
        print("Decorator 2")
        return func(*args, **kwargs)
    return wrapper

@decorator1
@decorator2
def my_function():
    print("Inside function")

my_function()
# Output: "Decorator 2", "Decorator 1", "Inside function"

You can also chain decorators together by calling them one after the other.

 
my_function = decorator1(decorator2(my_function))

It's important to note that the decorator will not be applied when the function is defined, but when it is called.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →