Document Python Functions with Dostrings
2 min readFeb 26, 2021
- The aim of this tutorial🔍 is to show how to build help for Python functions using docstrings
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
"""
- access help from the REPL
>>> 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