Apply a single decorator to multiple functions

左心房为你撑大大i 提交于 2019-12-10 18:47:41

问题


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

回答1:


If you want to make the "long" function call only once and decorate all three functions with the result, just do exactly that.

my_patch = patch('somelongmodulename.somelongmodulefunction')

@my_patch
def test_a(patched):
    pass

@my_patch
def test_b(patched):
    pass



回答2:


If you want to get fancy, you can modify 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])


来源:https://stackoverflow.com/questions/30563807/apply-a-single-decorator-to-multiple-functions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!