Effective Python - 59 Specific Ways to Write Better Python.

Chapter 7 - Collaboration

Book by Brett Slatkin. Summary notes by Tyler Banks.

Item 49: Write Docstrings for Every Function, Class, and Module

  • You can add documentation by providing a docstring immediately after the def statement of a function
In [4]:
def palindrome(word):
    """Return True if the given word is a palindrome."""
    return word == word[::-1]

#Retrieve the docstring with __doc__
print(repr(palindrome.__doc__))
'Return True if the given word is a palindrome.'

Documenting Modules

  • Modules should have a top level docstring. Should be three double quotes to start and end (""")
  • First line should be a single sentence describing modules purpose.
  • Paragrams following should detail everything the user should know
  • Ex:
In [11]:
# words.py
#!/usr/bin/env python3
"""Library for testing words for various linguistic patterns.
Testing how words relate to each other can be tricky sometimes!
This module provides easy ways to determine when words you’ve
found have special properties.
Available functions:
- palindrome: Determine if a word is a palindrome.
- check_anagram: Determine if two words are anagrams.
"""
print()

Documenting Classes

  • First line is the single sentence purpose of the class
  • Following classes should detail class operation
  • Important public attributes and methods should be highlighted in the docstring
  • Ex:
In [14]:
class Player(object):
    """Represents a player of the game.
    Subclasses may override the ‘tick’ method to provide
    custom animations for the player’s movement depending
    on their power level, etc.
    Public attributes:
    - power: Unused power-ups (float between 0 and 1).
    - coins: Coins found during the level (integer).
    """
    def __init__():
        self._power = 0
        self._coins = 0
        return
    
    @property
    def coins():
        return self._coins
    
    @coins.setter
    def coins(value):
        if value < 0:
            raise ValueError("Can't be less than 0")
        self._coins = value

Documenting Functions

  • First line is a single sentence description
  • Paragrams following should describe behaviors and arguments for the funciton
  • Return values should be mentioned
  • Exceptions that callers must handle as part of the funciton's interface should be explained
  • Ex:
In [15]:
def find_anagrams(word, dictionary):
    """Find all anagrams for a word.
    
    This function only runs as fast as the test for
    membership in the ‘dictionary’ container. It will
    be slow if the dictionary is a list and fast if
    it’s a set.
    
    Args:
        word: String of the target word.
        dictionary: Container with all strings that
            are known to be actual words.
            
    Returns:
        List of anagrams that were found. Empty if
        none were found.
    """
    return
  • If function has no args a single sentence is good
  • If no return, leave it out, don't say returns None

Item 50: Use Packages to Organize Modules and Provide Stable APIs

In [ ]: