I am trying to document a Python class that has some class-level member variables, but I could not get it appropriately documented using reST/Sphinx.
The code is this:
class OSM:
"""Some blah and examples"""
url = 'http://overpass-api.de/api/interpreter' # URL of the Overpass API
sleep_time = 10 # pause between successive queries when assembling OSM dataset
But I get this output (see the green circled area, where I would like to have some text describing both variables, as above).
I apologize for the blurring, but part of the example is somewhat sensitive
You have several options to document class level variables.
Put a comment that starts with #:
before the variable, or on the same line. (Uses only autodoc.)
Perhaps the easiest choice. If needed you can customize the value using :annotation:
option. If you want to type-hint the value use #: type:
.
Put a docstring after the variable.
Useful if the variable requires extensive documentation.
Document the variable in the class docstring. (Uses sphinx-napoleon extension, shown in the example.)
This has the drawback that the variable's value will be omitted. Since it's a class level variable your IDE's static type checker may complain if you don't prefix the variable with cls.
or class_name.
. The distinction is however convenient because instance variables can also be documented in the class docstring.
The following example shows all three options. The .rst
has additional complexity to illustrate the neededautodoc
functionalities. Type hints were included in all cases but can also be omitted.
class OSM:
"""Some blah and examples"""
#: str: URL of the Overpass API.
url = 'http://overpass-api.de/api/interpreter'
#: int: pause between successive queries when assembling OSM dataset.
sleep_time = 10
class OSM2:
"""Some blah and examples.
Attributes:
cls.url (str): URL of the Overpass API.
"""
url = 'http://overpass-api.de/api/interpreter'
sleep_time = 10
"""str: Docstring of sleep_time after the variable."""
Corresponding .rst
OSM module
==========
.. automodule:: OSM_module
:members:
:exclude-members: OSM2
.. autoclass:: OSM2
:no-undoc-members:
:exclude-members: sleep_time
.. autoattribute:: sleep_time
:annotation: = "If you want to specify a different value from the source code."
The result: