[英]Apply a single decorator to multiple functions
我已经搜索了这个,但是我看到的结果却恰恰相反:将多个装饰器应用到单个函数中。
我想简化这种模式。 有没有办法将这个单个装饰器应用于多个功能? 如果没有,我怎么能重写上面的重复次数呢?
from mock import patch
@patch('somelongmodulename.somelongmodulefunction')
def test_a(patched):
pass # test one behavior using the above function
@patch('somelongmodulename.somelongmodulefunction')
def test_b(patched):
pass # test another behavior
@patch('somelongmodulename.somelongmodulefunction')
def test_c(patched):
pass # test a third behavior
from mock import patch
patched_name = 'somelongmodulename.somelongmodulefunction'
@patch(patched_name)
def test_a(patched):
pass # test one behavior using the above function
@patch(patched_name)
def test_b(patched):
pass # test another behavior
@patch(patched_name)
def test_c(patched):
pass # test a third behavior
如果你想让“long”函数只调用一次,并用结果装饰所有三个函数,那就这样做吧。
my_patch = patch('somelongmodulename.somelongmodulefunction')
@my_patch
def test_a(patched):
pass
@my_patch
def test_b(patched):
pass
如果你想获得幻想,你可以修改globals()
。 下面的一般想法应该有效。
test_pattern = re.compile(r'test_\w+')
test_names = [name for name in globals().keys() if test_pattern.match(name)]
for name in test_names:
globals()[name] = decorate(globals()[name])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.