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?
A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. Such a docstring becomes the __doc__ special attribute of that object. All modules should normally have docstrings, and all functions and classes exported by a module should also have docstrings.
Class method docstrings should contain the following: A brief description of what the method is and what it's used for. Any arguments (both required and optional) that are passed including keyword arguments. Label any arguments that are considered optional or have a default value.
Docstrings for Python ClassesThe subclasses, constructors, and methods should each have their own docstrings.
Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. As you can see, even for a relatively simple function, documenting using comments quickly makes it unpleasant and difficult to read.
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__()
.
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