如何在python中做条件装饰器

如何在python中做条件装饰器

本文介绍了如何在python中做条件装饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以有条件地修饰一个函数。例如,我想用计时器函数( timeit )装饰函数 foo(),只有do_performance_analysis是 True (请参见下面的伪代码)。

Is it possible to decorator a function conditionally. For example, I want to decorate the function foo() with a timer function (timeit) only doing_performance_analysis is True (see the psuedo-code below).

if doing_performance_analysis:
  @timeit
  def foo():
    """
    do something, timeit function will return the time it takes
    """
    time.sleep(2)
else:
  def foo():
    time.sleep(2)


推荐答案

装饰器是简单的可调用函数,它们返回替换项,可以选择是相同的函数,包装器或完全不同的东西。这样,您可以创建一个条件装饰器:

Decorators are simply callables that return a replacement, optionally the same function, a wrapper, or something completely different. As such, you could create a conditional decorator:

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

现在您可以像这样使用它了:

Now you can use it like this:

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

装饰器也可以是一个类:

The decorator could also be a class:

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)

这里的 __ call __ 方法与第一个示例中返回的 decorator()嵌套函数以及封闭的<$此处的c $ c> dec 和 condition 参数作为参数存储在实例上,直到应用装饰器为止。

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 parameters here are stored as arguments on the instance until the decorator is applied.

这篇关于如何在python中做条件装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 06:38