[英]Parsing function docstring in sphinx.autodoc format
I have many functions in Python of the type:我在 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
And I need to parse the docstring to have a dictionary something like:而且我需要解析文档字符串以获得类似以下内容的字典:
{
'sdesc' : 'My function.',
'params' : [('one', 'My one argument.'), ('two', 'My two argument.')],
'rtype' : 'Something nice.'
}
I can use sphinx.util.docstrings.prepare_docstring
as follows:我可以使用
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.', '']
I could create my own parser, maybe using regex for params and rtype, and stuff.我可以创建自己的解析器,也许对 params 和 rtype 以及其他东西使用正则表达式。
But is there a better way to do it or a better approach?但是有没有更好的方法或更好的方法呢? How
sphinx.ext.autodoc
does it? sphinx.ext.autodoc
是怎么做的? Any other advice on how to parse this kind of docstrings?关于如何解析这种文档字符串的任何其他建议?
openstack/rally 's parse_docstrings()
(permalink) take a function's docstring in reStructuredText (reST) format as an input and returns 4 values-short_description, long_description, params and returns openstack/rally的
parse_docstrings()
(永久链接)以 reStructuredText (reST) 格式的函数文档字符串作为输入并返回 4 个值——short_description、long_description、params 和返回
For eg if the function and its docstring is例如,如果函数及其文档字符串是
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
"""
Then parse_docstrings() function will return-然后 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"
}
You can modify the above function as per your needs.您可以根据需要修改上述功能。
EDIT:编辑:
This question had two years without a response.这个问题已经两年没有回应了。 See the accepted response for a better option.
请参阅已接受的回复以获得更好的选择。
OLD:老的:
I ended up using regular expressions.我最终使用了正则表达式。 The particular system used by Sphinx of nested Nodes , where each node type has to parse their children is not very useful for my purposes.
嵌套Nodes的 Sphinx 使用的特定系统,其中每个节点类型都必须解析它们的子节点,对我的目的来说不是很有用。 If someone care, this is the regex I used:
如果有人关心,这是我使用的正则表达式:
param_regex = re.compile(
'^:param (?P<type>\w+)? (?P<param>\w+): (?P<doc>.*)$'
)
pip install docstring-parser
support both ReST-style and Google-style docstrings,支持 ReST 风格和 Google 风格的文档字符串,
see https://github.com/rr-/docstring_parser for details详见https://github.com/rr-/docstring_parser
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.