如何在修饰函数的文档中用真实签名替换*args
和**kwargs
?
假设我有以下装饰器和装饰函数:
import functools
def mywrapper(func):
@functools.wraps(func)
def new_func(*args, **kwargs):
print('Wrapping Ho!')
return func(*args, **kwargs)
return new_func
@mywrapper
def myfunc(foo=42, bar=43):
"""Obscure Addition
:param foo: bar!
:param bar: bla bla
:return: foo + bar
"""
return foo + bar
因此,调用 print(myfunc(3, 4))
给我们:
Wrapping Ho!
7
到目前为止一切顺利。我还希望包含 myfunc
的库用 Sphinx 正确记录。
但是,如果我通过以下方式将函数包含在我的 sphinx html 页面中:
.. automodule:: mymodule
:members: myfunc
它实际上会显示为:
myfunc(*args, **kwargs)
晦涩的加法
- 参数:
- foo:酒吧!
- bar:bla bla
- 返回: 富+酒吧
如何去掉标题中的通用myfunc(*args, **kwargs)
?这应该替换为 myfunc(foo=42, bar=43)。我如何更改 sphinx 或我的装饰器 mywrapper
以便在文档中保留默认关键字参数?
编辑:
正如指出的那样,这个问题之前已经被问过,但答案并不是很有帮助。
但是,我有一个想法,想知道这是否可能。 Sphinx 是否设置了一些环境变量来告诉我的模块它实际上是由 Sphinx 导入的?如果是这样,我可以简单地猴子修补我自己的包装器。如果我的模块是由 Sphinx 导入的,我的包装器会返回原始函数而不是包装它们。因此,签名得以保留。
最佳答案
我为 functools.wraps
想出了一个猴子补丁。
因此,我只是将其添加到项目文档的 sphinx source
文件夹中的 conf.py
脚本中:
# Monkey-patch functools.wraps
import functools
def no_op_wraps(func):
"""Replaces functools.wraps in order to undo wrapping.
Can be used to preserve the decorated function's signature
in the documentation generated by Sphinx.
"""
def wrapper(decorator):
return func
return wrapper
functools.wraps = no_op_wraps
因此,当通过 make html
构建 html 页面时,functools.wraps
被这个装饰器 no_op_wraps
替换,它除了简单地什么都不做返回原始函数。
关于python - 在 Sphinx 文档中保留包装/修饰的 Python 函数的默认参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28366818/