以sphinx.autodoc格式解析函数docstring

时间:2014-03-06 00:33:10

标签: python python-sphinx docstring

我在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.', '']

我可以创建自己的解析器,也可以使用正则表达式用于params和rtype,以及其他东西。

但有没有更好的方法来做到这一点或更好的方法? sphinx.ext.autodoc如何做到这一点?关于如何解析这种文档字符串的任何其他建议?

3 个答案:

答案 0 :(得分:10)

openstack/rallyparse_docstrings() (permalink)  将reStructuredText(reST)格式的函数文档字符串作为输入并返回4个值 - short_description,long_description,params并返回

例如如果函数及其docstring是

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"
}

您可以根据需要修改上述功能。

答案 1 :(得分:2)

编辑:

这个问题有两年没有回复。请参阅已接受的回复以获得更好的选择。


OLD:

我最终使用了正则表达式。 Sphinx使用的嵌套节点的特定系统,其中每个节点类型必须解析其子节点对我的目的而言并不是很有用。如果有人关心,这是我使用的正则表达式:

param_regex = re.compile(
    '^:param (?P<type>\w+)? (?P<param>\w+): (?P<doc>.*)$'
)

答案 2 :(得分:0)

pip install docstring-parser

同时支持ReST样式和Google样式的文档字符串,

有关详细信息,请参见https://github.com/rr-/docstring_parser

相关问题