python decorator extract参数

我是装饰者的新手,并尝试编写一个允许我获取命名参数的参数,如果它存在,否则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)
点赞