Search code examples
pythonpython-sphinxdocstring

docstring in class or __init__ constructor?


There seem to be two places where you can put docstrings for a class:

  1. Right under the class definition:

    class MyClass:
        """Summary of MyClass.
    
        Body.
        """
    
  2. Right under the __init__ constructor:

    class MyClass:
        def __init__(self, arg1, arg2):
            """Summary of MyClass.
    
            Body.
            """
    

Which is preferred? Or is it okay to have both?


Solution

  • They can both exist, since they are both intended for different things.

    The docstring for a class should summarize its behavior and list the public methods and instance variables. If the class is intended to be subclassed, and has an additional interface for subclasses, this interface should be listed separately (in the docstring). The class constructor should be documented in the docstring for its __init__ method. Individual methods should be documented by their own docstring.

    Emphasis mine. This reference is from PEP 257 -- Docstring Conventions