python - 切换装饰器

标签 python decorator

打开和关闭装饰器的最佳方式是什么,而无需实际去每个装饰器并将其注释掉?假设您有一个基准装饰器:

# deco.py
def benchmark(func):
  def decorator():
    # fancy benchmarking 
  return decorator

在你的模块中是这样的:

# mymodule.py
from deco import benchmark

class foo(object):
  @benchmark
  def f():
    # code

  @benchmark
  def g():
    # more code

这很好,但有时您不关心基准测试,也不想要开销。我一直在做以下事情。添加另一个装饰器:

# anothermodule.py
def noop(func):
  # do nothing, just return the original function
  return func

然后注释掉导入行并添加另一个:

# mymodule.py
#from deco import benchmark 
from anothermodule import noop as benchmark

现在基准测试是在每个文件的基础上切换的,只需更改相关模块中的导入语句。可以独立控制各个装饰器。

有更好的方法吗?如果根本不必编辑源文件,并指定在其他地方的哪些文件中使用哪些装饰器,那就太好了。

最佳答案

您可以将条件添加到装饰器本身:

def use_benchmark(modname):
    return modname == "mymodule"

def benchmark(func):
    if not use_benchmark(func.__module__):
        return func
    def decorator():
        # fancy benchmarking 
    return decorator

如果你在 mymodule.py 中应用这个装饰器,它将被启用;如果你在 othermodule.py 中应用它,它不会被启用。

关于python - 切换装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14636350/

相关文章:

python - 将字符串拆分为字母和数字

python - Django - 捕获异常

python - 当类 def 在另一个文件中时使用 Python 装饰器?

zend-framework - 如何在一个 Zend_Form 中连续放置 2 个按钮

python - 无法制作自定义 Django View 装饰器(带参数)

javascript - 带有属性装饰器的 TypeScript 类就像静态的一样

python - 即使 DAG 未运行, Airflow 变量也会更新

python - 有没有办法等待从当前脚本(使用 subprocess.Propen())调用的另一个 python 脚本直到它完成?

python - Linux进程崩溃后如何重新运行?

python - 用@staticmethod 修饰 __call__