Documentation Strings

Documentation Strings

Remember docstrings? PEP 257 talks about how to write them.

Docstrings for Classes

We can document not only functions and modules but also classes in Python!

Let’s document our whole bank_account module:

"""Utilities and objects for managing bank accounts."""


class BankAccount:

    """Bank account including an account balance."""

    def __init__(self, balance=0):
        """Open an account."""
        self.balance = balance
        print("Account opened.")
        self.print_balance()

    def deposit(self, amount):
        """Increase the account balance."""
        self.balance += amount
        print(f"${amount} deposited.")
        self.print_balance()

    def withdraw(self, amount):
        """Decrease the account balance."""
        self.balance -= amount
        print(f"${amount} withdrawn.")
        self.print_balance()

    def transfer(self, other_account, amount):
        """Move money from our account to the given account."""
        self.withdraw(amount)
        other_account.deposit(amount)

    def print_balance(self):
        """Print the current account balance."""
        print(f"Account balance is ${self.balance}.")

    def __str__(self):
        """Return a human-readable explanation of account."""
        return f"Account with balance of ${self.balance}"

    def __repr__(self):
        """Return a developer-readable representation of our account."""
        return f"BankAccount(balance={self.balance})"

Docstrings can be used on functions, classes, and modules. They must be the first string in each of these.

We can see all this documentation using help:

>>> import bank_account
>>> help(bank_account)