匿名设置中的参数装饰。
在许多可能的“嵌套”语法糖装饰的两种变化中被提出。它们之间的区别在于执行wrt到目标函数的顺序,并且它们的效果通常是独立的(不相互作用)。
装饰器允许在目标函数执行之前或之后“注入”自定义函数。
这两个函数的调用都发生在一个元组中。默认情况下,返回值是目标函数的结果。
语法糖装饰@first_internal(send_msg)('…end')要求版本>= 3.9,请参阅PEP 614放松对装饰器的语法限制。
functools使用。以保留目标函数的文档字符串。
from functools import wraps
def first_external(f_external):
return lambda *args_external, **kwargs_external:\
lambda f_target: wraps(f_target)(
lambda *args_target, **kwargs_target:
(f_external(*args_external, **kwargs_external),
f_target(*args_target, **kwargs_target))[1]
)
def first_internal(f_external):
return lambda *args_external, **kwargs_external:\
lambda f_target: wraps(f_target)(
lambda *args_target, **kwargs_target:
(f_target(*args_target, **kwargs_target),
f_external(*args_external, **kwargs_external))[0]
)
def send_msg(x):
print('msg>', x)
@first_internal(send_msg)('...end') # python >= 3.9
@first_external(send_msg)("start...") # python >= 3.9
def test_function(x):
"""Test function"""
print('from test_function')
return x
test_function(2)
输出
msg> start...
from test_function
msg> ...end
讲话
composition decorators, such as pull-back and push-forward (maybe in a more Computer Science terminology: co- and resp. contra-variant decorator), could more useful but need ad-hoc care, for example composition rules, check which parameters go where, etc
syntactic sugar acts as a kind of partial of the target function: once decorated there is no way back (without extra imports) but it is not mandatory, a decorator can be used also in its extended forms, i.e. first_external(send_msg)("start...")(test_function)(2)
the results of a workbench with timeit.repeat(..., repeat=5, number=10000) which compare the classical def and lambda decoration shows that are almost equivalent:
for lambda: [6.200810984999862, 6.035239247000391, 5.346362481000142, 5.987880147000396, 5.5331550319997405] - mean -> 5.8206
for def: [6.165001932999985, 5.554595884999799, 5.798066574999666, 5.678178028000275, 5.446507932999793] - mean -> 5.7284
naturally an non-anonymous counterpart is possible and provides more flexibility