Docstrings – RST markup and documentation tools
All Python code should have docstrings at the module, class, and method levels. Not every single method requires a docstring. Some method names are really well chosen, and little more needs to be said about them. Most times, however, documentation is essential for clarity.
Python documentation is often written using ReStructured Text (RST) markup.
Throughout the code examples in the book, however, we'll omit docstrings. It keeps the book to a reasonable size. This gap has the disadvantage that it makes docstrings seem optional. They're emphatically not optional.
We'll emphasize this again. Docstrings are essential.
The docstring material is used by Python in the following three ways:
- 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 epydoc can produce elegant documentation extracts
Because of the relative simplicity of RST, it's quite easy to write good docstrings. We'll take a look at documentation and the expected markup in detail in Chapter 18, Quality and Documentation. For now, however, we'll provide a quick example of what a docstring might look like:
def factorial( n ): """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 RST markup for parameters and return values. It includes an additional note about a profound limitation. It also includes the doctest
output that can be used to validate the implementation using the doctest
tool. There are numerous markup features that can be used to provide additional structure and semantic information.