我是装饰器的新手,正在尝试编写一个允许我获取命名参数(如果存在)的方法,否则可以获取Exception之类的东西。
解释:
# my decorator!
def test_mem(key, modifier):
def deco(func):
@wraps(func)
def wrapper(*args, **kwargs):
# something here, s.t.
# print(args + modifier) <------
return func(*args, **kwargs)
return wrapper
return deco
@test_mem('username', modifier = '_allowed')
def myfunc(arg1, username = None, stuff = None):
# logic, this code is always run!
return 'Done'
myfunc(1, 3)
>>>> '3_allowed'
myfunc(1, username = 3)
>>>> '3_allowed'
myfunc(1, stuff = [])
>>>> Exception
当我对其进行编码时,示例1和示例2是互斥的,而示例1可以使示例2失效,反之亦然。我正在尝试使用它来创建一些自动键。
您可能还需要考虑inspect.getcallargs()
。在装饰器内,您可以使用:
dictionary = inspect.getcallargs(func, *args, **kwargs)
dictionary['username'] # Gets you the username, default or modifed
要从链接的Python文档复制:
>>> from inspect import getcallargs
>>> def f(a, b=1, *pos, **named):
... pass
>>> getcallargs(f, 1, 2, 3)
{'a': 1, 'named': {}, 'b': 2, 'pos': (3,)}
>>> getcallargs(f, a=2, x=4)
{'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()}
>>> getcallargs(f)
Traceback (most recent call last):
...
TypeError: f() takes at least 1 argument (0 given)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句