Documenting both class and constructor in Sphinx

I lost an hour of my life today trying to figure out why Sphinx would not document a class inside a module specified by :automodule:.

I learnt two things today.

Firstly, Sphinx will not document a class automatically as part of :automodule: if the class itself doesn’t have a docstring. You can force the class to be displayed by having an additional :autoclass:directive though.

If the class does have a doc string, it will be displayed including the documentation of its regular (ones without a leading _ in the name) methods. It will still not show the constructor though.

To display the constructor, I first thought I would add the :special-members: option to the :automodule: directive. But that didn’t work very well, as it showed various unnecessary private functions as well, e.g. _weakref.

I finally discovered that the best way to get the constructor documentation displayed was using the autoclass_content config in the sphinx config file.

autoclass_content = 'both'

As per the documentation,

This value selects what content will be inserted into the main body of an autoclass directive. The possible values are:

  • “class”: Only the class’ docstring is inserted. This is the default. You “can still document init as a separate method using automethod or “the members option to autoclass.
  • “both”: Both the class’ and the init method’s docstring are concatenated and inserted.
  • “init”: Only the init method’s docstring is inserted.
Using Python to update a required field while performing a transition in Jira The Borg design pattern