SmC*_*lar 8 python documentation decorator python-sphinx python-decorators
我怎么能代替*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
Run Code Online (Sandbox Code Playgroud)
因此,通话print(myfunc(3, 4))给我们:
Wrapping Ho!
7
Run Code Online (Sandbox Code Playgroud)
到现在为止还挺好.我还希望我的库包含myfunc与Sphinx一起正确记录的文件.但是,如果我通过以下方式将我的函数包含在我的sphinx html页面中:
.. automodule:: mymodule
:members: myfunc
Run Code Online (Sandbox Code Playgroud)
它实际上会显示为:
模糊的加法
我怎样才能摆脱myfunc(*args, **kwargs)标题中的泛型?这应该被myfunc替换(foo = 42,bar = 43).如何更改sphinx或我的装饰器mywrapper,以便在文档中保留默认关键字参数?
编辑:
正如之前所指出的那样,这个问题已被提出,但答案并没有那么有用.
但是,我有一个想法,并想知道这是否可行.Sphinx是否设置了一些环境变量来告诉我的模块它实际上是由Sphinx导入的?如果是这样,我可以简单地修补我自己的包装.如果我的模块是由Sphinx导入的,我的包装器将返回原始函数而不是包装它们.因此,签名得以保留.
我想出了一个猴子补丁functools.wraps。因此,我只是将其添加到了conf.py项目文档的sphinx source文件夹中的脚本中:
# 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
Run Code Online (Sandbox Code Playgroud)
因此,当通过构建html页面时make html,functools.wraps此装饰器no_op_wraps将替换它,该装饰器只返回原始函数,什么也不做。
| 归档时间: |
|
| 查看次数: |
1502 次 |
| 最近记录: |