Docstrings Best Practices in Functions

Import Libraries

from collections import defaultdict


A docstring is a string at the beginning of the function body that explains how the function 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

Coding on the job you'll frequently look back at previous code, refactor/improve upon previous code, read other people's code and someone will likely have questions on your code.

What is one of the best ways to reduce anxiety with all the to-dos above... document your code well!

Well-written docstrings are just one example that'll make your code easier to read for you and others, and make your life so much easier.

What Doctsrings Should Include

Succinct info on the function's:

  1. Logic
  2. Arguments and their data types
  3. Return values and their data type

Example: Duplicates in a List

Let's say we have a list of numbers.

groceries = ["eggs", "carrots", "eggs", "spinach", "carrots"]

Notice how eggs and carrots are repeated twice.

Function to count the number of occurences for each item

def count_occurences_items(list_of_items):
    Given a list of items, count the occurences of each item by looping over 
    list_of_items and creating a defaultdict data structure of item:count pairs.

    Keyword arguments:
    list_of_values -- any list of items
    defaultdict_count_of_item_occurences = defaultdict(int)
    for item in list_of_items:
        defaultdict_count_of_item_occurences[item] += 1
    return defaultdict_count_of_item_occurences
grocery_item_occurences = count_occurences_items(groceries)
defaultdict(int, {'carrots': 2, 'eggs': 2, 'spinach': 1})

Function to print duplicated values and count of occurences

def print_multiple_item_occurences(count_item_occurences):
    Print in pretty format of items with multiple occurences by looping over
    count_item_occurences and checking if values >= 2.

    Keyword arguments:
    count_item_occurences -- dictionary structure of item:count pairs
    for key, value in count_item_occurences.items():
        if value >= 2:
            print("{0} - quantity of {1}".format(key, value))
eggs - quantity of 2
carrots - quantity of 2