Python Documentation – How to Split Between Docstrings and Sphinx

documentationpython

I'm using a combination of docstrings and Sphinx to document my Python programs. With Sphinx's autodoc, I can write a lot of documentation into the source as docstrings. Is there any standard for how much documentation to put in each?

For example,

case 1 is index.rst

.. automodule:: foo
   :members:

and foo.py

"""documentation"""

class Foo:
"""documentation""""

    def bar(self, baz):
        """more documentation"""

case 2 index.rst

.. automodule:: foo

and foo.py

"""documentation

.. autoclass:: Foo

"""

class Foo:
"""documentation

.. automethod:: bar

""""

    def bar(self, baz):
        """more documentation"""

case 3 index.rst

.. automodule:: foo
   .. autoclass:: Foo
      .. automethod:: bar

and foo.py

"""documentation

Classes:
    Foo

"""

class Foo:
"""documentation

Methods:
    bar

""""

    def bar(self, baz):
        """more documentation"""

The 1 is easy to maintain, but the docstrings in the source lacks information.
The 2 puts that information into the source docstrings, but it's a bit harder to maintain and is a bit harder to read.
The 3 is easy to read and has complete documentation in the source code, but is very hard to maintain, and when you use sphinx to generate the documentation, some information is repeated. (It'll look something like:

foo:
    documentation
    classes:
        Foo

    Foo:
        documentation
        methods:
            baz
        baz

Best Answer

The Python standard library keeps all of its Sphinx documentation separate, forgoing the autodoc feature entirely, and uses much more brief docstrings in the source files. Thus, the following practice is perhaps best:

  • Docstrings in source code should not use Sphinx directives, using only light reST formatting for readability. Because (good) Python code is quite clear on its own, keep docstrings informative but simple. These should be primarily for project devs and anyone digging into the source code.
  • Actual end-user (or developers for libraries) documentation should be taken care of by Sphinx. Use autodoc when suitable, adhering to the above.
Related Topic