gpt4 book ai didi

python - 如何定义为函数/方法调用提供内插文档字符串的装饰器

转载 作者:太空狗 更新时间:2023-10-30 01:34:49 24 4
gpt4 key购买 nike

我对装饰器还不够好,还不能做到这一点......是否可以定义一个装饰器live_doc,它允许我在方法或函数调用后获得一个内插的文档字符串,填充包含实际参数和返回值。

@live_doc("f was called with %d, %s and returned %d")
def f(x, y):
x + len(y)

在下面的代码之后:

f(3, "marty")

d = f.doc

d 应该是“f 被调用为 3,“marty”,并返回 8”。我宁愿在访问 f.doc 之前不构建字符串,但肯定需要在某处存储调用 args 和返回值。

最佳答案

这是一个比较通用的解决方案,可以处理您的原始文档字符串作为模板,并维护有关装饰功能的其他信息(就像它的名字一样):

from functools import wraps

def live_doc(func):
template = func.__doc__
@wraps(func)
def wrapper(*args, **kwargs):
ret_val = func(*args, **kwargs)
args_pretty = ", ".join(repr(a) for a in args)
kw_pretty = ", ".join("%s=%r" % (k, v) for k, v in kwargs.items())
signature = ", ".join(x for x in (args_pretty, kw_pretty) if x)
name = func.__name__
wrapper.__doc__ = template % locals()
return ret_val
return wrapper

@live_doc
def f(x, y):
"""%(name)s was called with %(signature)s and returned %(ret_val)r."""
return x + len(y)

在首次调用 f 之前,交互式解释器中的 help(f) 会为您提供:

Help on function f in module __main__:

f(*args, **kwargs)
%(name)s was called with %(signature)s and returned %(ret_val)r.

调用后,您将获得:

f(*args, **kwargs)
f was called with 3, 'marty' and returned 8.

或者使用更通用的函数,展示kwargs:

@live_doc
def q(*args, **kwargs):
"""%(name)s was called with %(signature)s and returned %(ret_val)r."""
return len(args) + len(kwargs)

>>> q(1, 2, 3, a=7, b="foo")
5
>>> help(q)
q(*args, **kwargs)
q was called with 1, 2, 3, a=7, b='foo' and returned 5.

显然,您可以在 wrapper 中创建您想要在模板中使用的任何变量。

关于python - 如何定义为函数/方法调用提供内插文档字符串的装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13618786/

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