首页 > 解决方案 > 使用 Sphinx 时,如何记录没有文档字符串的成员?

问题描述

我正在为我发布的包编写文档,我发现你的文档越全面,人们就越容易找到你的包使用 (duh)。实际上,我很喜欢写代码的所有功能和细节。

但是,我对如何为类级变量编写与 Sphinx 兼容的文档完全感到困惑。特别是,我有一些我想记录的枚举类,但对于我的一生,我无法想出一种将文档附加到枚举值的方法。结果是我的文档中有这些冗长而尴尬的部分,除了变量名之外没有任何文档。

我意识到使用直接的文档字符串是不可能的,因为变量没有文档字符串,但是 Sphinx 肯定有某种功能吗?否则,人们将如何记录诸如常量之类的公开可见的值?

标签: pythonvariablesconstantspython-sphinxmember

解决方案


虽然这是真的 Python 变量不能有文档字符串。使用 Sphinxautodoc扩展,autodataandautoattribute指令允许记录变量和常量。请注意,在模块级变量或类成员的情况下,用途是不同的。

此外,如果您想为文档中的成员仲裁一个不同于编程值的值,最好的方法是使用 annotations

autodata 和 autoattribute 支持 annotation 选项。

Sphinx 可以获取关于变量声明的注释并将它们包含在文档中(虽然这些注释不是文档字符串,但它们将在文档中呈现)。让我们看一个最小的工作示例:

源文件your_module_name.py

"""This modules documentation."""

ONE_CONSTANT = "A constant value."
"""Turns out the comment is rendered as a docstring if we put it underneath."""

#: Lets try it like this
TWO_CONSTANTS = 2000


class OneClass:
    """Commenting members of a class."""

    #: Lets try the third comment like this.
    THREE_CONSTANTS = 3000

    #: Lets try the forth comment like this.
    FOUR_CONSTANTS = 4000

对应your_module_name.rst

your\_module\_name module
=========================

.. automodule:: your_module_name
   :members: ONE_CONSTANT, TWO_CONSTANTS

   .. autodata:: ONE_CONSTANT
      :annotation: =this annotation

   .. autoclass:: OneClass
      :members:
      :undoc-members:
      :show-inheritance:

生成的 HTML:

在此处输入图像描述

最后说明:这可能会强制调整您以前用于在源代码中注释变量的一些约定。此外,如果使用注释,您将不希望包含该成员autodataautomodule避免它被包含两次。


推荐阅读