簡體   English   中英

將單個裝飾器應用於多個功能

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM