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

前端 未结 6 624
刺人心
刺人心 2020-11-29 02:08

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 whet

6条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 02:36

    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
    

提交回复
热议问题