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

前端 未结 6 591
刺人心
刺人心 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:20

    If the decorators don't take additional arguments, you could use

    def compose(f, g):
        return lambda x: f(g(x))
    
    combined_decorator = compose(decorator1, decorator2)
    

    Now

    @combined_decorator
    def f():
        pass
    

    will be equivalent to

    @decorator1
    @decorator2
    def f():
        pass
    

提交回复
热议问题