[英]python decorator extract argument
I am new to decorators and trying to write one that allows me to get the named argument, if it exists, otherwise Exception or something. 我是装饰器的新手,正在尝试编写一个允许我获取命名参数(如果存在)的方法,否则可以获取Exception之类的东西。
To explain: 解释:
# 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
When I coded it, my example 1 and example 2 were mutually exclusive, when example 1 worked example 2 broke and vice versa. 当我对其进行编码时,示例1和示例2是互斥的,而示例1可以使示例2失效,反之亦然。 I am trying to use this to create some automatic keys.
我正在尝试使用它来创建一些自动键。
You may also want to consider inspect.getcallargs()
. 您可能还需要考虑
inspect.getcallargs()
。 Inside your decorator, you can use: 在装饰器内,您可以使用:
dictionary = inspect.getcallargs(func, *args, **kwargs)
dictionary['username'] # Gets you the username, default or modifed
To copy from the linked Python docs: 要从链接的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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.