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