Document Python Functions with Dostrings

1. addition of self-documentation to your own module

  • API documentation in Python uses a facility called docstrings
  • document functions, modules, and classes
  • requirement: must be the first statement in the blocks for these constructs
  • docstring is a literal string occurring as the first string within the named block
  • docstring is a place where most code documentation should live
  • ❌ it does not explain how code works
  • ✅ it does show how to consume facilities the module provides (list parameters, methods, basic concerns)

2. provide an example of a function fetching words from an URL

  • use triple-quotes
  • valid also for single-lined docstrings → can expand easily to add more detail
import sys
from urllib.request import urlopen
def fetchwords():
""" Fetch a list of words from URL """
story = urlopen("http://sixty-north.com/c/t.txt")
story_words = []

3. tools

  • e.g. Sphinx is a tool that builds HTML documentation from Python docstrings
  • each tool, however, mandates its preferred docstring format

3.1. Google’s Python Styleguide format

  • amendable to being machine parsed
  • readable at console
  • they go into detail to describe docstrings for
  • ✅ module
  • ✅ function
  • ✅ class

4. Example

  • an example for a function
def fetchwords():
"""Fetch a list of words from URL.

Args:
url: The URL of UTF-8 text document

Returns:
A list of strings containing words from the document
"""
>>> from words import *
>>> help(fetchwords)
Help on function fetchwords in module words:
fetchwords()
Fetch a list of words from URL.
Args:
url: The URL of UTF-8 text document
Returns:
A list of strings containing words from the document

5. list used sources

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pavol Kutaj

Pavol Kutaj

Infrastructure Support Engineer/Technical Writer (Snowplow Analytics) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com