【发布时间】:2021-01-29 21:04:45
【问题描述】:
之前有人问过类似的问题:
functools.wraps 在装饰器中创建了一个名为__wrapped__ 的魔术方法,它允许访问被包装的函数。但是,当您有多个装饰器时,这将返回一个内部装饰器,而不是原始函数。
如何避免或绕过多个装饰器?
【问题讨论】:
标签: python python-3.x unit-testing pytest
之前有人问过类似的问题:
functools.wraps 在装饰器中创建了一个名为__wrapped__ 的魔术方法,它允许访问被包装的函数。但是,当您有多个装饰器时,这将返回一个内部装饰器,而不是原始函数。
如何避免或绕过多个装饰器?
【问题讨论】:
标签: python python-3.x unit-testing pytest
要绕过或避免多个装饰器并访问最里面的函数,请使用以下递归方法:
def unwrap(func):
if not hasattr(func, '__wrapped__'):
return func
return unwrap(func.__wrapped__)
在 pytest 中,您可以在 conftest.py 中使用此功能,并通过以下方式访问整个测试:
# conftest.py
import pytest
@pytest.fixture
def unwrap():
def unwrapper(func):
if not hasattr(func, '__wrapped__'):
return func
return unwrapper(func.__wrapped__)
yield unwrapper
# my_unit_test.py
from my_module import decorated_function
def test_my_function(unwrap):
decorated_function_unwrapped = unwrap(decorated_function)
assert decorated_function_unwrapped() == 'something'
【讨论】: