We saw previously how it was possible to ask at the REPL for help on Python functions. Let's look at how to add this self-documenting capability to our own module.
API documentation in Python uses a facility called docstrings. Docstrings are literal strings which occur as the first statement within a named block, such as a function or module. Let's document the fetch_words()
function:
def fetch_words(url): """Fetch a list of words from a URL.""" with urlopen(url) as story: story_words = [] for line in story: line_words = line.decode('utf-8').split() for word in line_words: story_words.append(word) return story_words
We use triple-quoted strings even for single-line docstrings because they can be easily expanded to add more detail.
One Python convention for docstrings is documented in PEP 257, although it is not widely adopted. Various tools, such as Sphinx, are available to build HTML documentation from Python docstrings...