Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I combine two decorators into a single one in Python?

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.

like image 904
Ludo Avatar asked Mar 23 '11 17:03

Ludo


People also ask

Can you add two decorators Python?

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.

How many decorators are there in Python?

In fact, there are two types of decorators in Python — class decorators and function decorators — but I will focus on function decorators here.

Are decorators Pythonic?

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.

What order are decorators called Python?

When the interpreter calls the decorated method the decorators are called from top --> bottom.


2 Answers

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 
like image 143
Jochen Ritzel Avatar answered Oct 13 '22 12:10

Jochen Ritzel


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 
like image 34
Thanatos Avatar answered Oct 13 '22 12:10

Thanatos