我从中学到了stack_overflow_entry在 Python 中装饰器按照它们在源代码中出现的顺序应用。
那么下面的代码片段应该如何表现呢?
@unittest.skip("Something no longer supported")
@skipIf(not something_feature_enabled, "Requires extra crunchy cookies to run")
def test_this():
....
第一个装饰器(如下所示)要求测试运行器完全跳过 test_this()
@unittest.skip("Something no longer supported")
虽然第二个装饰器要求测试运行器有条件地跳过运行 test_this()。
@skipIf(不是 something_feature_enabled,“需要额外的脆 cookies 才能运行”)
那么这是否意味着 test_this 根本不会运行,除非我们先放置条件跳过装饰器?
还有,Python有没有办法定义装饰器的依赖执行?例如
@skipIf("Something goes wrong")
@skipIf(not something_feature_enabled, "Requires extra crunchy cookies to run")
@log
@send_email
def test_this():
....
如果 @skipIf("Something goes wrong") 是 ,这个想法是启用 。@log 和 @send_email 的执行是的
如果我遗漏了一些非常明显的东西,我们深表歉意。
请您参考如下方法:
我认为您可能遗漏了一个关键点:装饰器只是一个传递函数并返回函数的函数。
所以,这些是相同的:
@log
def test_this():
pass
def test_this():
pass
test_this = log(test_this)
同样地:
@skip("blah")
def test_this():
pass
def test_this():
pass
test_this = skip("blah")(test_this)
一旦您理解了这一点,您所有的问题都会变得非常简单。
首先,是的,skip(…) 被用来修饰 skipIf(…)(test),所以如果它跳过它修饰的东西, test 永远不会被调用。
定义装饰器调用顺序的方法是按照您希望它们调用的顺序编写它们。
如果你想动态地做到这一点,你会首先通过动态应用装饰器来做到这一点。例如:
for deco in sorted_list_of_decorators:
test = deco(test)
Also, is there any way in Python to define dependent execution of decorators?
不,他们都被处决了。与您的要求更相关的是,每个装饰器都应用于装饰函数,而不是装饰器。
但您始终可以将装饰器传递给条件装饰器:
def decorate_if(cond, deco):
return deco if cond else lambda f: f
然后:
@skipIf("Something goes wrong")
@decorate_if(something_feature_enabled, log)
@decorate_if(something_feature_enabled, send_email)
def test_this():
pass
很简单,对吧?
现在,如果 something_feature_enabled 为真,将应用 log 和 send_email 装饰器;否则,将应用不以任何方式装饰函数并仅返回它不变的装饰器。
但是如果你不能通过装饰器怎么办,因为函数已经被装饰了?好吧,如果你定义每个装饰器来暴露它包装的函数,你总是可以打开它。如果你总是使用 functools.wraps(如果你没有理由不这样做,你通常应该这样做——即使你有这样的理由,你也可以很容易地用这种方式模拟),包装函数是始终以 __wrapped__ 的形式提供。因此,您可以编写一个有条件地轻松移除最外层装饰的装饰器:
def undecorate_if(cond):
def decorate(f):
return f.__unwrapped__ if cond else f
return decorate
再说一遍,如果您尝试动态地执行此操作,您可能会进行动态装饰。因此,一个更简单的解决方案是跳过不需要的装饰器,方法是在应用它们之前将它们从 decos 可迭代对象中移除。
