Dark theme

Docstrings


Documentation generators have been around since the late 80s, though perhaps the height of the art is the Java version, javadoc, which has influenced many subsequent versions. Python comes with a version called PyDoc, though more sophisticated sites tend to be generated using additional software like Sphinx (which comes with Anaconda).

Many documentation generators build documentation directly from the source code, and you can do this in PyDoc. In order to do it, you need to write comments in a specific style called "docstrings". The docstring style is detailed in PEP-0257, which you should definitely read if you're going to produce coder-friendly Python. Here's an example of a file with docstrings: docs.py. Before we look at this as a webpage, however, let's look at another use for the docstring: within the Python console.


Save the file, and either open it in Spyder or run it from the command line thus:
python -i docs.py
This latter will run the file, loading variables etc. into memory, and then leave you at the Python prompt so you can explore them.

Python will automatically parse docstrings it finds, and build them into a hidden variable called __doc__ associated with the relevant object, for example: add.__doc__. You can then access these by typing help(object_name); try typing:
help(add)
help(Calc)

(NB: the standard prompt in Spyder seems to struggle to pick up functions – use an iPython console instead.)

This service provides a quick access to the API for most of the core Python. Try:
help(print)
help(property)

In iPython, what you should also notice is that when you start typing a function and get as far as the first parenthesis, suggestions come up as to what you might like to enter in the way of arguments.

Both these functions are useful when trying to work out what arguments to pass into a function and what might come back, as well as the "public" (i.e. not dunder-named, except __init__) methods inside different classes. However, docstrings are also, and perhaps more commonly, accessible through documentation webpages.