Python Beginner Concepts Tutorial

Docstrings Best Practices in Functions

A docstring is a documentation string at the beginning of the class, function or function body that briefly explains how it works.

Every function you create ought to have a docstring. They're in triple-quoted strings and allow for multi-line text.

Why Docstrings Are So Important

As a programmer, you'll likely spend a significant amount of time reading and trying to understand documentation and others' code than writing your own code on a greenfield project. You'll struggle to understand variable names, method operations and how functions work. It can be frustrating. How do you remedy this?

Document your code well with docstrings!

3 Ways to Write Docstrings

I'll illustrate 3 acceptable ways go write docstrings given the complexity of your code. In these 3 ways, I'll use simple examples.

Docstring Method #1

This docstring is a short one-line docstring meant for minimal complexity functions.

In [1]:
def multiply_all_numbers(list_of_items):
    """multiply all numbers by one another and return product"""
    multiplication_product = 1
    for item in list_of_items:
        multiplication_product *= item
    return multiplication_product

Docstring Method #2

This docstring is the most common method and can be used for a function with any level of complexity.

In [7]:
from collections import defaultdict

def count_occurences_items(list_of_items):
    """Given a list of items, count the occurences of each item in key-value pairs in a defaultdict.

    :param list_of_item: list of items    
    :return count_item_occurences: defaultdict of keys of item names and values being count of occurences in input list
    """
    count_item_occurences = defaultdict(int)
    for item in list_of_items:
        count_item_occurences[item] += 1
    return count_item_occurences

Docstring Method #3

Below I use a form of docstrings I first noticed built into the PyCharm (by Jetbrains) IDE. This is the most detailed version that I would especially recommend for complex functions.

In [6]:
def count_occurences_items(list_of_items):
    """Given a list of items, count the occurences of each item in key-value pairs in a defaultdict.

    :param list_of_item: list of items
    :type list_of_item: list
    
    :return count_item_occurences: keys of item names and values being count of occurences in input list
    :type count_item_occurences: defaultdict
    """
    count_item_occurences = defaultdict(int)
    for item in list_of_items:
        count_item_occurences[item] += 1
    return count_item_occurences

More details on using docstrings in Python on the official documentation page.