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

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


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__().


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), sofrom 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.


I personally try to use the google styleguide when possible

When you create a new instance with __init__ it should be documented what member variables are initialized. Then other people know what they can expect when they need to access them later in their code.

Sample from the google styleguide:

class SampleClass(object):    """Summary of class here.    Longer class information....    Longer class information....    Attributes:        likes_spam: A boolean indicating if we like SPAM or not.        eggs: An integer count of the eggs we have laid.    """    def __init__(self, likes_spam=False):        """Inits SampleClass with blah."""        self.likes_spam = likes_spam        self.eggs = 0    def public_method(self):        """Performs operation blah."""