【问题标题】:Parsing function docstring in sphinx.autodoc format以 sphinx.autodoc 格式解析函数文档字符串
【发布时间】:2014-03-06 00:33:10
【问题描述】:

我在 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

而且我需要解析文档字符串以获得类似于以下内容的字典:

{
    '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 是怎么做到的?有关如何解析此类文档字符串的任何其他建议?

【问题讨论】:

  • 由于Sphinx是开源的,你可以找到autodoc模块here

标签: python python-sphinx docstring


【解决方案1】:

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

例如如果函数及其文档字符串是

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

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

【讨论】:

  • 两年后终于得到了很好的回应。谢谢!
  • 看起来这个答案中引用的函数不支持备用param type 规范格式:当参数指定为:param str name: User's name(而不是:param name: User's name :type name: str)时,它不会注意到这样的参数。另一个答案中使用的正则表达式不会发生这种情况。
  • @MarSoft - 我将它分叉以支持类型 - github.com/SamuelMarks/doctrans/blob/37810ff/doctrans/info.py
【解决方案2】:

编辑:

这个问题两年没有回复。查看接受的回复以获得更好的选择。


旧:

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

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

【讨论】:

  • 接受的答案似乎很可靠,但我在安装 Rally 时遇到了麻烦。恕我直言,此答案有效且易于实施。
  • @MikeyE - 你不需要安装 Rally,只需取出一个 Python 文件,info.py
【解决方案3】:

pip install docstring-parser

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

详情请见https://github.com/rr-/docstring_parser

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多