toggling decorators

后端 未结 7 1904
伪装坚强ぢ
伪装坚强ぢ 2021-01-04 18:37

What\'s the best way to toggle decorators on and off, without actually going to each decoration and commenting it out? Say you have a benchmarking decorator:



        
7条回答
  •  情歌与酒
    2021-01-04 18:43

    I would implement a check for a config file inside the decorator's body. If benchmark has to be used according to the config file, then I would go to your current decorator's body. If not, I would return the function and do nothing more. Something in this flavor:

    # deco.py
    def benchmark(func):
      if config == 'dontUseDecorators': # no use of decorator
          # do nothing
          return func
      def decorator(): # else call decorator
          # fancy benchmarking 
      return decorator
    

    What happens when calling a decorated function ? @ in

    @benchmark
    def f():
        # body comes here
    

    is syntactic sugar for this

    f = benchmark(f)
    

    so if config wants you to overlook decorator, you are just doing f = f() which is what you expect.

提交回复
热议问题