I want to autogenerate documentation to my code from docstrings. I have some basic class meant to store some data:
class DataHolder: """ Class to hold some data Attributes: batch: Run without GUI debug (bool): Show debug messages """ batch: bool = False debug: bool = False name: str = 'default' """Object name""" version: int = 0 """int: Object version"""
My rst
file:
DataHolder ========== .. autoclass:: data_holder.DataHolder :members:
I have documented each attribute in a different way to show the difference, here is the output:
It seems like Sphinx cannot connect the Attributes
section with the real attributes, that's why it cannot display their default value.
The final output I would like to achieve is the outcome as for the version
field with the docstring defined as for batch
. I want to display the attribute name with default value and type, but taken from type annotations. Looks like Sphinx is ignoring the type annotations in this case.
My sphinx extensions:
extensions = [ 'sphinx.ext.viewcode', 'sphinx.ext.autodoc', 'sphinxcontrib.napoleon', ]
What can I do to achieve such behavior? I can't find any good examples for such use case.
For example, it's possible to create a dictionary containing values and docstrings for the attributes and then add the contents to the class __dict__ and docstring towards the end of the class declaration; this would alleviate the need to type the attribute names and values twice.
Accessing the attributes of a classgetattr() − A python method used to access the attribute of a class. hasattr() − A python method used to verify the presence of an attribute in a class. setattr() − A python method used to set an additional attribute in a class.
Class attributes are attributes which are owned by the class itself. They will be shared by all the instances of the class. Therefore they have the same value for every instance. We define class attributes outside all the methods, usually they are placed at the top, right below the class header.
Method 1: To get the list of all the attributes, methods along with some inherited magic methods of a class, we use a built-in called dir() . Method 2: Another way of finding a list of attributes is by using the module inspect .
I do not think you can put an Attribute section inside of your docstring to get your desired results.
I tried giving each attribute a doc comment and specified the type and desired comment.
class DataHolder: """ Class to hold some data Each attribute needs its own doc comment with its type """ #: bool: Run without Gui batch = False #: bool: Show debug messages debug = False #: str: Object Name name = 'default' #: int: Object Version version = 0
This gives the following output and a nice Type description of each output.
Take a look here:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With