sphinx能否根据实际实施验证文档

J. *_*Doe 6 python python-sphinx

我正在将sphinx文档添加到几个项目中,但我担心未来的开发人员在方法界面更改时不会严格更新文档.有没有办法让sphinx根据方法定义中实际指定的内容验证所描述的参数列表?

例如,假设我使用sphinx-quickstart设置了sphinx,添加了autodoc,并且我正在尝试构建以下"模块":

def product(arg_one, arg_two):
    '''
    :param arg_one: an object to be multiplied by arg_two
    :type arg_one: Object

    :param arg_two: an integer which defines the number of arg_one to return
    :type arg_two: integer

    :returns: The product of arg_one and arg_two

    :raises: TypeError
    '''
    return arg_one * arg_two
Run Code Online (Sandbox Code Playgroud)

而且,从现在起一周后,Bob Doe更新产品如下:

def product(value, number, catch_errors=False):
    '''
    :param arg_one: an object to be multiplied by arg_two
    :type arg_one: Object

    :param arg_two: an integer which defines the number of arg_one to return
    :type arg_two: integer

    :returns: The product of arg_one and arg_two

    :raises: TypeError
    '''
    try:
        return value * number
    except TypeError as exc:
        if catch_errors:
            return None
        raise
Run Code Online (Sandbox Code Playgroud)

现在,sphinx文档不正确 - 它缺少新的catch_errors字段,并且已重命名变量.但是,跑步

sphinx-build . ./_build
Run Code Online (Sandbox Code Playgroud)

第二次没有发现问题 - 它只是报道

Running Sphinx v1.6.5
loading pickled environment... done
building [mo]: targets for 0 po files that are out of date
building [html]: targets for 0 source files that are out of date
updating environment: 0 added, 0 changed, 0 removed
looking for now-outdated files... none found
no targets are out of date.
build succeeded.
Run Code Online (Sandbox Code Playgroud)

我希望(或希望)Sphinx能够根据方法的实际代码验证docstring,并且在文档和实现不同步时失败(或至少以某种方式指示).

如果狮身人面像不具备此功能,是否有其他选择?我知道Python 3中函数注释,但我们目前支持Python 2和Python 3,所以这不是一个选项.

Jos*_*osh 1

经过一番研究后,我认为我能轻松找到的最接近的工具是darglint,但它最近在 Github 上进入了存档模式(2022 年 12 月),因此无法保证甚至不可能提供长期支持。

受 torchvision讨论的启发,一种选择是使用Sphinx-Napoleonpydocstyle,几乎所有功能都关闭,除了D417检查文档字符串中缺少的参数。

因此pydocstyle可以检查缺少的参数,但目前无法检查额外的参数。

编辑:似乎 pylint 可以使用扩展来做到这一点https://pylint.pycqa.org/en/latest/user_guide/checkers/extensions.html#pylint-extensions-docparams但各种 linter 和样式检查器之间存在一些功能重叠所以你可能需要选择你要搭配的。

为了捕获重命名的参数,您还可以在测试中强制执行 100% 的覆盖率,但这不会捕获对非关键字参数的重构。

其他一些可用的软件包:

doctest非常适合检查文档字符串示例是否正确运行,但它不进行任何签名验证。因此,如果您设置像问题中的示例一样的默认参数,它仍然会通过 doctest。如果您在所有示例中都使用了关键字参数,则可以使用它作为检查,但它有点冗长。

interrogate能够检查文档字符串覆盖率,但除此之外没有太多功能(据我所知?)我不确定其他工具是否确实可以检查覆盖率,因此这可能是一个可以串联使用的好工具。