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

Ludo picture Ludo · Mar 23, 2011 · Viewed 13.5k times · Source

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.

Answer

Jochen Ritzel picture Jochen Ritzel · Mar 23, 2011

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