我在 Python 中有很多这样的函数:
def foobar(one, two):
"""
My function.
:param int one: My one argument.
:param int two: My two argument.
:rtype: Something nice.
"""
return 100 + one + two
我需要解析 docstring 以获得类似这样的字典:
{
'sdesc' : 'My function.',
'params' : [('one', 'My one argument.'), ('two', 'My two argument.')],
'rtype' : 'Something nice.'
}
我可以使用 sphinx.util.docstrings.prepare_docstring
如下:
>>> prepare_docstring(foobar.__doc__)
['My function.', ':param int one: My one argument.', ':param int two: My two argument.', ':rtype: Something nice.', '']
我可以创建自己的解析器,也许对参数和 rtype 等使用正则表达式。
但是是否有更好的方法或更好的方法呢? sphinx.ext.autodoc
是如何做到的?关于如何解析此类文档字符串的任何其他建议?
最佳答案
openstack/rally的 parse_docstrings()
(permalink)
将 reStructuredText (reST) 格式的函数文档字符串作为输入并返回 4 个值——short_description、long_description、params 和 returns
例如如果函数及其文档字符串是
def sample(self, task, deployment=None):
"""Start benchmark task.
Implement sample function's long description.
:param task: Path to the input task file.
:param deployment: UUID or name of the deployment
:returns: NIL
"""
然后 parse_docstrings() 函数将返回-
{ "short_description" : "Start benchmark task.",
"long_description" : "Implement sample function's long description.",
"params": [ { "name" : "task", "doc": "Path to the unput task file" },
{ "name" : "deployment", "doc" : "UUID or name of the deployment" } ]
"returns" : "NIL"
}
您可以根据需要修改上述功能。
关于python - 以 sphinx.autodoc 格式解析函数文档字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22212470/