gpt4 book ai didi

python装饰器提取参数

转载 作者:太空宇宙 更新时间:2023-11-03 11:31:10 25 4
gpt4 key购买 nike

我是装饰器的新手,正在尝试编写一个允许我获取命名参数(如果存在)的装饰器,否则会出现异常或其他问题。

解释:

# 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 崩溃,反之亦然。我正在尝试使用它来创建一些自动 key 。

最佳答案

您可能还想考虑 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)

关于python装饰器提取参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19648129/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com