Is there a way to combine two decorators into one new decorator in python?
I realize I can just apply multiple decorators to a function, but I was curious as to whether there's some simple way to combine two into a new one.
So, here in this post, we are going to learn about Decorator Chaining. Chaining decorators means applying more than one decorator inside a function. Python allows us to implement more than one decorator to a function.
In fact, there are two types of decorators in Python — class decorators and function decorators — but I will focus on function decorators here.
Decorators are a very powerful and useful tool in Python since it allows programmers to modify the behaviour of a function or class. Decorators allow us to wrap another function in order to extend the behaviour of the wrapped function, without permanently modifying it.
When the interpreter calls the decorated method the decorators are called from top --> bottom.
A bit more general:
def composed(*decs): def deco(f): for dec in reversed(decs): f = dec(f) return f return deco
Then
@composed(dec1, dec2) def some(f): pass
is equivalent to
@dec1 @dec2 def some(f): pass
Yes. See the definition of a decorator, here.
Something like this should work:
def multiple_decorators(func): return decorator1(decorator2(func)) @multiple_decorators def foo(): pass
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With