How can I use named arguments in a decorator?(如何在修饰器中使用命名参数?)
本文介绍了如何在修饰器中使用命名参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有以下函数:
def intercept(func):
# do something here
@intercept(arg1=20)
def whatever(arg1,arg2):
# do something here
我希望仅当arg1为20时才触发截取。我希望能够将命名参数传递给函数。我如何才能做到这一点?
这里有一个小代码示例:
def intercept(func):
def intercepting_func(*args,**kargs):
print "whatever"
return func(*args,**kargs)
return intercepting_func
@intercept(a="g")
def test(a,b):
print "test with %s %s" %(a,b)
test("g","d")
这引发以下异常类型错误:intercept()获取意外的关键字参数‘a’
推荐答案
from functools import wraps
def intercept(target,**trigger):
def decorator(func):
names = getattr(func,'_names',None)
if names is None:
code = func.func_code
names = code.co_varnames[:code.co_argcount]
@wraps(func)
def decorated(*args,**kwargs):
all_args = kwargs.copy()
for n,v in zip(names,args):
all_args[n] = v
for k,v in trigger.iteritems():
if k in all_args and all_args[k] != v:
break
else:
return target(all_args)
return func(*args,**kwargs)
decorated._names = names
return decorated
return decorator
示例:
def interceptor1(kwargs):
print 'Intercepted by #1!'
def interceptor2(kwargs):
print 'Intercepted by #2!'
def interceptor3(kwargs):
print 'Intercepted by #3!'
@intercept(interceptor1,arg1=20,arg2=5) # if arg1 == 20 and arg2 == 5
@intercept(interceptor2,arg1=20) # elif arg1 == 20
@intercept(interceptor3,arg2=5) # elif arg2 == 5
def foo(arg1,arg2):
return arg1+arg2
>>> foo(3,4)
7
>>> foo(20,4)
Intercepted by #2!
>>> foo(3,5)
Intercepted by #3!
>>> foo(20,5)
Intercepted by #1!
>>>
functools.wraps做维基上的简单修饰符;更新修饰符的__doc__、__name__等属性。
这篇关于如何在修饰器中使用命名参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:如何在修饰器中使用命名参数?
基础教程推荐
猜你喜欢
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 求两个直方图的卷积 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 包装空间模型 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
