Search code examples
pythondecorator

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.


Solution

  • 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