如何在 python 中做一个条件装饰器?

新手上路,请多包涵

是否可以有条件地装饰函数? For example, I want to decorate the function foo() with a timer function ( timeit ), but only when doing_performance_analysis condition is True ,像这样:

     if doing_performance_analysis:
      @timeit
      def foo():
        """
        Do something, e.g. sleep, and let timeit
        return the time it takes
        """
        time.sleep(2)
    else:
      def foo():
        time.sleep(2)

原文由 cfpete 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 818
2 个回答

装饰器是简单的可调用对象,返回一个替换,可选的相同函数、包装器或完全不同的东西。因此,您可以创建一个条件装饰器:

 def conditional_decorator(dec, condition):
    def decorator(func):
        if not condition:
            # Return the function unchanged, not decorated.
            return func
        return dec(func)
    return decorator

现在你可以像这样使用它:

 @conditional_decorator(timeit, doing_performance_analysis)
def foo():
    time.sleep(2)

装饰器也可以是一个类:

 class conditional_decorator(object):
    def __init__(self, dec, condition):
        self.decorator = dec
        self.condition = condition

    def __call__(self, func):
        if not self.condition:
            # Return the function unchanged, not decorated.
            return func
        return self.decorator(func)

Here the __call__ method plays the same role as the returned decorator() nested function in the first example, and the closed-over dec and condition 此处的参数在应用装饰器之前存储为实例的参数。

原文由 Martijn Pieters 发布,翻译遵循 CC BY-SA 4.0 许可协议

装饰器只是一个应用于另一个函数的函数。您可以手动应用它:

 def foo():
   # whatever
   time.sleep(2)

if doing_performance_analysis:
    foo = timeit(foo)

原文由 Blckknght 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题