Documentation – sphinx and RST markup

All Python code should have docstrings at the module, class and method level. Not every single method requires a docstring. Some method names are really well chosen, and little more needs to be said. Most times, however, documentation is essential for clarity.

Python documentation is often written using the reStructuredText (RST) markup.

Throughout the code examples in the book, however, we'll omit docstrings. The omission keeps the book to a reasonable size. This gap has the disadvantage of making docstrings seem optional. They're emphatically not optional.

This point is so important, we'll emphasize it again: docstrings are essential.

The docstring material is used three ways by Python:

  • The internal help() function displays the docstrings.
  • The doctest tool can find examples in docstrings and run them as test cases.
  • External tools, such as sphinx and pydoc, can produce elegant documentation extracts from these strings.

Because of the relative simplicity of RST, it's quite easy to write good docstrings. We'll look at documentation and the expected markup in detail in Chapter 18, Coping with the Command Line. For now, however, we'll provide a quick example of what a docstring might look like:

def factorial(n: int) -> int:
"""
Compute n! recursively.

:param n: an integer >= 0
:returns: n!

Because of Python's stack limitation, this won't
compute a value larger than about 1000!.

>>> factorial(5)
120
"""
if n == 0:
return 1
return n*factorial(n-1)

This shows the RST markup for the n parameter and the return value. It includes an additional note about limitations. It also includes a doctest example that can be used to validate the implementation using the doctest tool. The use of :param n: and :return: identifies text that will be used by the sphinx tool to provide proper formatting and indexing of the information.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset