gpt4 book ai didi

带有装饰函数参数的python装饰器

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

当我用 @ 包装一个函数时,如何使包装函数看起来和感觉起来与包装函数完全一样?尤其是 help(function)

部分代码:

>>> def wraps(f):
def call(*args, **kw):
print('in', f, args, kw) # example code. I need to transfer the arguments to another process and pickle them.
return f(*args, **kw)
return call

>>> def g():pass

>>> @wraps
def f(a, b = 1, g = g, *args, **kw):
pass

>>> help(f)
Help on function call in module __main__:

call(*args, **kw) # this line bothers me. It should look different, look below

>>> def f(a, b = 1, g = g, *args, **kw):
pass

>>> help(f)
Help on function f in module __main__:

f(a, b=1, g=<function g at 0x02EE14B0>, *args, **kw) # help(f) should look like this.

动机:当帮助窗口弹出时,当我输入 f( * plopp * 我看到 (a, b = 1, g = g, *args, **kw).(在本例中是在 IDLE Python Shell 中)

我查看了 inspect 模块,它可以帮助我进行良好的格式化。问题仍然存在:我如何使用参数来做到这一点..

def f(d = {}): 这样的默认可变参数传递不需要工作,因为我将参数传输到另一个进程并且身份无论如何都会丢失。

最佳答案

functools.wraps 可用于复制函数的名称和文档字符串。从头开始复制原始函数签名要困难得多。

如果您使用第三方 decorator module , 然而, 然后

import decorator


@decorator.decorator
def wraps(f):
def call(*args, **kw):
print('in', f, args, kw)
return f(*args, **kw)
return call


def g():pass

@wraps
def f(a, b = 1, g = g, *args, **kw):
pass

help(f)

产量

Help on function f in module __main__:

f(a, b=1, g=<function g>, *args, **kw)

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

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