使用Sphinx时,如何记录没有docstring的成员?

2024-05-16 00:41:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为我发布的软件包编写文档,我发现您的文档越全面,人们就越容易使用您的软件包(duh)。事实上,我非常喜欢编写代码的所有特性和细节

然而,如何为类级变量编写与Sphinx兼容的文档让我完全不知所措。特别是,我想记录一些enum类,但就我的一生而言,我无法找到将文档附加到枚举值的方法。结果是我得到了我文档中的这些long and awkward sections,其中除了变量名之外没有任何文档

我意识到使用直接的docstring是不可能的,因为变量没有docstring,但是Sphinx肯定有一些关于这方面的功能?否则,人们将如何记录公开可见的值(如常量)


Tags: and方法代码文档sphinx记录enum特性
1条回答
网友
1楼 · 发布于 2024-05-16 00:41:01

确实,Python变量不能有docstring。使用Sphinxautodoc扩展,autodataautoattribute指令允许记录变量和常量。请注意,对于模块级变量或类成员,用法是不同的

此外,如果您希望仲裁文档中与编程值不同的成员值,最好的方法是using annotations

autodata and autoattribute support the annotation option.

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:

enter image description here

最后一点注意:这可能会迫使您修改以前在源代码中注释变量时使用的一些约定。另外,如果使用注释,您将不希望在autodataautomodule中包含该成员,以避免它被包含两次

相关问题 更多 >