Ale*_*lex 5 python variables constants member python-sphinx
我正在为我发布的包编写文档,我发现您的文档越全面,人们就越容易找到您的包来使用(废话)。事实上,我在热情地编写代码的所有功能和细节方面获得了很多乐趣。
然而,我对如何为类级变量编写与 Sphinx 兼容的文档感到完全困惑。特别是,我有一些想要记录的枚举类,但我一生都找不到将文档附加到枚举值的方法。结果是我的文档中有这些又长又尴尬的部分,除了变量名之外没有任何文档。
我意识到使用直接文档字符串是不可能的,因为变量没有文档字符串,但 Sphinx 肯定有某种功能吗?否则,人们如何记录公开可见的值(例如常量)?
虽然 Python 变量确实不能有文档字符串。使用 Sphinxautodoc扩展,autodata和autoattribute指令允许记录变量和常量。请注意,在模块级变量或类成员的情况下,用法是不同的。
此外,如果您想在文档中仲裁与编程值不同的成员值,最好的方法是使用注释。
autodata 和 autoattribute 支持注释选项。
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
Run Code Online (Sandbox Code Playgroud)
相应的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:
Run Code Online (Sandbox Code Playgroud)
生成的 HTML:
最后注意事项:这可能会强制调整您之前在源代码中注释变量时使用的一些约定。另外,如果使用注释,您将不希望包含该成员autodata或automodule避免它被包含两次。