python - 以 sphinx.autodoc 格式解析函数文档字符串

标签 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.', '']

我可以创建自己的解析器,也许对参数和 rtype 等使用正则表达式。

但是是否有更好的方法或更好的方法呢? sphinx.ext.autodoc 是如何做到的?关于如何解析此类文档字符串的任何其他建议?

最佳答案

openstack/rallyparse_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/

相关文章:

python - 玛雅/Python : Creating Unique Commands in Loop-Generated UI

Python to_datetime(来自 3 列中的 int/float)

python - 如何超链接来自 Sphinx 中 Python 模块的方法?

python - sphinx-apidoc 用法 - 多个源 python 目录

python - 如何防止 Django 测试在文档字符串中运行示例?

python - 将 python doctest 放在代码文件的末尾?

python - pkg_resources 不从 python Egg 中提取文件

Python:将excel文件添加到access数据库

latex - 在编写手册/书籍方面,Sphinx 是否比 LaTex 更好?

javascript - 使用文档字符串