python装饰程序提取参数

python装饰程序提取参数,python,decorator,Python,Decorator,我是一个新的装饰,并试图写一个允许我得到命名参数,如果它存在,否则异常或其他东西 解释: # my decorator! def test_mem(key, modifier): def deco(func): @wraps(func) def wrapper(*args, **kwargs): # something here, s.t. # print(args + modifier) <-----

我是一个新的装饰,并试图写一个允许我得到命名参数,如果它存在,否则异常或其他东西

解释:

# 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

当我编码它时,我的示例1和示例2是互斥的,当示例1工作时,示例2坏了,反之亦然。我想用这个来创建一些自动键。

你也可以考虑一下。在装饰器内部,您可以使用:

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)
>>> 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)