Python Beginner Concepts Tutorial

Docstrings Best Practices in Functions

Import Libraries

In [4]:
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.

In [5]:
groceries = ["eggs", "carrots", "eggs", "spinach", "carrots"]

Notice how eggs and carrots are repeated twice.

Function to count the number of occurences for each item

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

    :param list_of_item: any list of items
    :returns: defaultdict_count_of_item_occurences: keys of item names and values being count of occurences
    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
In [7]:
grocery_item_occurences = count_occurences_items(groceries)
In [8]:
defaultdict(int, {'carrots': 2, 'eggs': 2, 'spinach': 1})

Function to print duplicated values and count of occurences

In [9]:
def find_multiple_item_occurences(count_item_occurences):
    Filter a dictionary to keep only key:value pairs in which the value is >= 2
    :param count_item_occurences: dictionary of item:count pairs
    :returns: duplicate_items: dictionary structure of item:count pairs for duplicate items
    duplicate_items = {}
    for key, value in count_item_occurences.items():
        if value >= 2:
            duplicate_items[key] = value
    return duplicate_items
In [10]:
{'eggs': 2, 'carrots': 2}