Is there a consensus what should be documented in the classes and __init__ docstrings?

causa prima picture causa prima · May 4, 2016 · Viewed 16.7k times · Source

I did not find any best practice about what should be documented in the classes and __init__ docstrings. Sometimes I find that the constructor arguments are already documented in the classes docstring, sometimes the are described in the __init__ docstring. I prefer describing the construction within the classes docstring, as this is what you call when creating a new instance. But what should be documented in the __init__ methods docstring then?


edit:

I know about the google styleguide and the google docstring style example, but both do not answer my question. The docstring style example does say

The __init__ method may be documented in either the class level docstring, or as a docstring on the __init__ method itself. Either form is acceptable, but the two should not be mixed. Choose one convention to document the __init__ method and be consistent with it.

But if I choose to put the docstring of the __init__ function into the class level docstring, what should the __init__ docstring contain?

Answer

Eric O Lebigot picture Eric O Lebigot · Sep 13, 2019

There is an official answer, in PEP 257 (the docstring PEP), which is arguably authoritative:

The class constructor should be documented in the docstring for its __init__ method.

This is quite logical, as this is the usual procedure for functions and methods, and __init__() is not an exception.

As a consequence, this puts the code and its documentation in the same place, which helps maintenance.

Finally, tools that display documentation to the user (like Jupyter, or the built-in Python shell command help()) are more likely to correctly display the documentation of your code. In practice, they do display the __init__() docstring automatically when you ask for help on the class, so this is one more reason to follow the official convention of putting the initialization documentation in __init__().