python - 使用 Sphinx 时,如何记录没有文档字符串的成员?
问题描述
我正在为我发布的包编写文档,我发现你的文档越全面,人们就越容易找到你的包使用 (duh)。实际上,我很喜欢写代码的所有功能和细节。
但是,我对如何为类级变量编写与 Sphinx 兼容的文档完全感到困惑。特别是,我有一些我想记录的枚举类,但对于我的一生,我无法想出一种将文档附加到枚举值的方法。结果是我的文档中有这些冗长而尴尬的部分,除了变量名之外没有任何文档。
我意识到使用直接的文档字符串是不可能的,因为变量没有文档字符串,但是 Sphinx 肯定有某种功能吗?否则,人们将如何记录诸如常量之类的公开可见的值?
解决方案
虽然这是真的 Python 变量不能有文档字符串。使用 Sphinxautodoc
扩展,autodata
andautoattribute
指令允许记录变量和常量。请注意,在模块级变量或类成员的情况下,用途是不同的。
此外,如果您想为文档中的成员仲裁一个不同于编程值的值,最好的方法是使用 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:
最后说明:这可能会强制调整您以前用于在源代码中注释变量的一些约定。此外,如果使用注释,您将不希望包含该成员autodata
或automodule
避免它被包含两次。
推荐阅读
- django - How to check active accordion based on object id?
- spring-boot - SSE emitters received timeout at client side onmessage
- c# - Problem with Confluent.Kafka.ConsumeException: Broker: Message size too large
- git - 在 Windows 上扫描 git
- security - 端口使用 nmap 扫描家庭网络,但无法理解 nmap 如何在连接超过 1 个设备时找到打开的端口
- .net - 为什么在发布 Web 应用程序时 Directory.build.props 不起作用
- c# - 'MvxWpfSetup
' 必须是具有公共无参数构造函数的非抽象类型 - mysql - 我们如何在mysql和php中启动连接
- javascript - 索引到非数组时的打字稿问题
- java - Gradle bootrun 报错 Web 服务器启动失败。端口 8080 已被使用,而 IntelliJ 在使用外部配置时运行良好