When using Sphinx, how can I document members that don't have docstrings?

被刻印的时光 ゝ 提交于 2021-02-08 08:37:17

问题


I'm writing documentation for package I've published, and I find the more thorough your documentation, the easier people find your package to use (duh). I'm actually having a lot of fun lovingly writing up all the features and details of my code.

However, I'm completely flummoxed by how to write Sphinx-compatible documentation for class-level variables. In particular, I've got some enum classes I'd like to document, but for the life of me I can't figure out a way to attach documentation to the enum values. The result is I've got these long and awkward sections of my documentation where there's no documentation except variable names.

I realize using straight docstrings is out of the question because variables don't have docstrings, but surely Sphinx has some sort of functionality around this? Otherwise, how would people document publicly visible values like constants?


回答1:


While it's true Python variables can't have docstrings. Using Sphinx autodoc extension, the autodata and autoattribute directives allow documenting variables and constants. Notice the use is different in case of a module level variable or a class member.

Additionally, should you want to arbitrate a value for the member in the documentation that is different from the programmatic value, the best way is using annotations.

autodata and autoattribute support the annotation option.

Sphinx can pick up comments on variable declarations and include them in the documentation (while those comments aren't docstrings they will be rendered in the documentation). Let's look at a minimal working example:

Source file 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

Corresponding 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:

The resulting HTML:

Final note: This may force adapting some conventions you previously used for commenting variables in your source code. Also, if using annotations you'll want to not include that member in autodata or automodule to avoid it being included twice.



来源:https://stackoverflow.com/questions/61314181/when-using-sphinx-how-can-i-document-members-that-dont-have-docstrings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!