Sobes.tech
Junior
210

Can multiple decorators be used for a single function?

Answer from AI

sobes.tech AI

Yes, it is possible to use multiple decorators sequentially. Decorators are applied from bottom to top.

Applying multiple decorators:

# Decorator 1
def decorator_one(func):
    def wrapper(*args, **kwargs):
        print("Before calling the function (decorator 1)")
        result = func(*args, **kwargs)
        print("After calling the function (decorator 1)")
        return result
    return wrapper

# Decorator 2
def decorator_two(func):
    def wrapper(*args, **kwargs):
        print("Before calling the function (decorator 2)")
        result = func(*args, **kwargs)
        print("After calling the function (decorator 2)")
        return result
    return wrapper

# Applying both decorators
@decorator_one
@decorator_two
def my_function():
    print("Inside my_function")

# Calling the function
my_function()

Execution order:

When calling my_function(), first @decorator_two is applied to my_function, then @decorator_one is applied to the result of @decorator_two.

Equivalent representation without the @ syntax:

def my_function():
    print("Inside my_function")

# Equivalent to @decorator_two
my_function = decorator_two(my_function)

# Equivalent to @decorator_one
my_function = decorator_one(my_function)

# Calling the function
my_function()

Output when executed:

Before calling the function (decorator 1)
Before calling the function (decorator 2)
Inside my_function
After calling the function (decorator 2)
After calling the function (decorator 1)

It is visible that the "wrapper" of decorator_two executes first (inner) around the call to my_function, and the "wrapper" of decorator_one executes outermost.