toggling decorators

后端 未结 7 1848
伪装坚强ぢ
伪装坚强ぢ 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 19:07

    I don't think anyone has suggested this yet:

    benchmark_modules = set('mod1', 'mod2') # Load this from a config file
    
    def benchmark(func):
      if not func.__module__ in benchmark_modules:
          return func
    
      def decorator():
        # fancy benchmarking 
      return decorator
    

    Each function or method has a __module__ attribute that is the name of the module where the function is defined. Create a whitelist (or blacklist if you prefer) of modules where benchmarking is to occur, and if you don't want to benchmark that module just return the original undecorated function.

    0 讨论(0)
提交回复
热议问题