I have a very simple class with 2 class variables and I want to effectively document the class variables -
class AzimuthalRhoPhi(Azimuthal):
r"""
Attributes:
rho (scalar, ``np.ndarray``, ``ak.Array``, etc.): The $\rho$ coordinate(s).
phi (scalar, ``np.ndarray``, ``ak.Array``, etc.): The $\phi$ coordinate(s).
"""
rho: ScalarCollection
phi: ScalarCollection
The docstring above does work but sphinx renders the class variables individually (and automatically) too. Rendered documentation (notice the extra rho
and phi
automatically generated by sphinx) -
This is the .rst
file -
.. automodule:: vector._methods
:members:
:undoc-members:
:show-inheritance:
:private-members:
Going through the following StackOverflow posts -
- How to remove static class variable using automodule with Sphinx?
- Documenting class-level variables in Python
I discovered that there are 4 ways in which I can accomplish this -
- Use comments above the class variable
- Use inline docstring
- Exclude the class variable from
.rst
file - Use
cls.variable_name
format
- Using comments above the class variable
Code -
class AzimuthalRhoPhi(Azimuthal):
#: scalar, ``np.ndarray``, ``ak.Array``, etc.: The $\rho$ coordinate(s).
rho: ScalarCollection
#: scalar, ``np.ndarray``, ``ak.Array``, etc.: The $\phi$ coordinate(s).
phi: ScalarCollection
Rendered documentation -
Notice how it type annotates the variables with Any
which I do not want. Plus, having all the documentation related to the class in the docstring makes it much more accessible, which makes me not want to use this method.
- Use inline docstring
Code -
class AzimuthalRhoPhi(Azimuthal):
rho: ScalarCollection
r"""scalar, ``np.ndarray``, ``ak.Array``, etc.: The $\rho$ coordinate(s)."""
phi: ScalarCollection
r"""scalar, ``np.ndarray``, ``ak.Array``, etc.: The $\phi$ coordinate(s)."""
Rendered documentation -
This method raises the exact same problems which were present in the first method.
- Exclude the class variables from
.rst
file
Code -
.. automodule:: vector._methods
:members:
:exclude-members: AzimuthalRhoPhi
:undoc-members:
:show-inheritance:
:private-members:
.. autoclass:: AzimuthalRhoPhi
:exclude-members: rho, phi
Rendered documentation -
Works like a charm! BUT!
- Brings the class to the top of the documentation
- I have a lot of such classes and doing this manually for every class feels redundant.
- Use
cls.variable_name
format
Code -
class AzimuthalRhoPhi(Azimuthal):
r"""
Attributes:
cls.rho (scalar, ``np.ndarray``, ``ak.Array``, etc.): The $\rho$ coordinate(s).
cls.phi (scalar, ``np.ndarray``, ``ak.Array``, etc.): The $\phi$ coordinate(s).
"""
rho: ScalarCollection
phi: ScalarCollection
Rendered documentation -
Does not work :(
Is there a way to hide the autogenerated doc of class variables? I only want to keep the docs written in the docstring but sphinx duplicates them in a way. Or do I have to choose one of the four methods mentioned above?