Is there a consensus what should be documented in the classes and __init__ docstrings?
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?
Solution 1:
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__()
.
Solution 2:
The actual usage of the class is initialized by a command like SampleClass(args)
, and no user is ever going to type in SampleClass.__init__(args)
, so
from an end-user perspective, when they are confused, they are much more likely to type
help(SampleClass)
instead of
help(SampleClass.__init__)
So I think it makes sense to put all documentation into SampleClass
's docstring.
And in __init__
's docstring put "Please see help(SampleClass)
for more info" just in case there's the off chance that someone (or some program) looks at it.