[英]Apply a single decorator to multiple functions
I've searched for this, but the results I've seen involve the opposite: applying multiple decorators to a single function. 我已经搜索了这个,但是我看到的结果却恰恰相反:将多个装饰器应用到单个函数中。
I'd like to simplify this pattern. 我想简化这种模式。 Is there a way to apply this single decorator to multiple functions? 有没有办法将这个单个装饰器应用于多个功能? If not, how can I rewrite the above to be less repetitious? 如果没有,我怎么能重写上面的重复次数呢?
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
If you want to make the "long" function call only once and decorate all three functions with the result, just do exactly that. 如果你想让“long”函数只调用一次,并用结果装饰所有三个函数,那就这样做吧。
my_patch = patch('somelongmodulename.somelongmodulefunction')
@my_patch
def test_a(patched):
pass
@my_patch
def test_b(patched):
pass
If you want to get fancy, you can modify globals()
. 如果你想获得幻想,你可以修改globals()
。 The general idea below should work. 下面的一般想法应该有效。
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.