sec05 - Chapter 6: Python Docstrings: How to Use Them for Better Code Documentation and Maintainability
スポンサーリンク

How to Add Docstrings Across Your Entire Python Project

Let’s add Docstrings to the Fortune Cookie project we’ve built so far. These docstrings describe the purpose of each module and function.

A module docstring is written at the top of the file.

# fortune.py
'''
Main program for the Fortune Cookie application.
Controls the flow of language selection and message display.
'''

import random

import manager.language_manager as lang_manager


def main():
    '''Execute the main process of the Fortune Cookie application.

    Prompts the user to select a language and then displays a random
    fortune message based on the user’s choice.

    Flow summary:
        1. Prompt the user to choose a language (Japanese / English).
        2. Retrieve messages and fortune texts from the corresponding
           language module.
        3. Display the fortune only when the user answers "y"
           to the question "Would you like to open a cookie?"

    Raises:
        KeyError: Raised when a required key is missing from the `MESSAGES`
            dict in the language module.
        Exception: Raised when an unexpected error occurs.
    '''
    try:
        # Choose language
        lang_code = input('Choose a language (jp/en): ')
        # Receive the language-specific module
        lang_module = lang_manager.get_language_module(lang_code)
        messages = lang_module.MESSAGES
        fortunes = lang_module.FORTUNES

# ~~~ Omitted below ~~~ #
# manager/language_manager.py
'''
Module for managing messages by language.

Based on the provided language code (e.g., 'jp', 'en'), this module
dynamically imports and returns the corresponding message module.
'''

import sys


def get_language_module(lang_code):
    '''Return the message module corresponding to the given language code.

    Based on the provided language code (`lang_code`), dynamically import
    the corresponding language module (`message.language_en` or
    `message.language_jp`).

    If an unsupported language code is provided, the Japanese module
    is returned by default.

    Args:
        lang_code (str): The language code ('en' or 'jp').

    Returns:
        module: The module object corresponding to the given language code.

    Raises:
        SystemExit: Raised to indicate abnormal termination when importing
            the message module fails.
    '''
    try:
        if lang_code == 'en':
            from message import language_en
            return language_en
        elif lang_code == 'jp':
            from message import language_jp
            return language_jp
        else:
            print('Unsupported language code. Using Japanese instead.')
            from message import language_jp
            return language_jp
    except ImportError as e:
        print('ImportError: Required message module not found.')
        print('Details:', e)
        print('Exiting the program.')
        sys.exit(1)  # Exit with non-zero status (indicates abnormal exit)

# ~~~ Omitted below ~~~ #
# message/language_en.py
'''
Module for managing English messages.

This module defines the English messages and fortune texts used
in the Fortune Cookie application.
'''

# MESSAGES is a dict containing text used in the app
MESSAGES = {
    'app_title': 'Fortune Cookie',  # string used for app title display
    'prompt_open': 'Would you like to open a cookie? (y/n): ',  # prompt to ask user action
    'fortune_prefix': 'Your fortune for today is:',  # prefix for fortune display
    'goodbye': 'See you tomorrow with more luck!'  # farewell message
}

# FORTUNES is a list of fortunes displayed randomly
FORTUNES = [
    'Great Fortune! A wonderful day awaits you.',
    'Fair Fortune. Keep steady progress.',
    'Little Fortune. Stay patient and try again.',
    'Bad Fortune... but tomorrow is another chance.'
]
# message/language_jp.py
'''
Module for managing Japanese messages.

This module defines the Japanese messages and fortune texts used
in the Fortune Cookie application.
'''

# MESSAGES is a dict containing text used in the app
MESSAGES = {
    'app_title': 'フォーチュンクッキー',  # string used for app title display
    'prompt_open': 'クッキーを開きますか? (y/n): ',  # prompt to ask user action
    'fortune_prefix': 'あなたの今日の運勢は:',  # prefix for fortune display
    'goodbye': 'また明日も幸運を!',  # farewell message
}

# FORTUNES is a list of fortunes displayed randomly
FORTUNES = [
    '大吉!最高の一日になりそうです!',
    '中吉。ちょっとした幸運が訪れるでしょう。',
    '小吉。小さな努力が実を結びます。',
    '凶...でも心配しすぎないでください。'
]

Adding docstrings across your project is extremely helpful during team development and handoffs. They provide a clear overview of “what functions and classes exist” and “what they do,” greatly improving maintainability and readability.

How to Review Docstrings and Use help()

How to Read Docstrings Using help()

Load each module as shown below and inspect its contents using help().

Add the following code inside the if __name__ == '__main__': block of fortune.py to review the information.

if __name__ == '__main__':
    # fortune module
    import sys
    help(sys.modules['__main__'])

    # language_manager module
    from manager import language_manager
    help(language_manager)

    # language_en module
    from message import language_en
    help(language_en)

To view the help() output for the fortune module (currently running as '__main__'), use sys.modules['__main__'].

Examples of Docstrings Displayed by help()

Result for fortune:

Help on module __main__:

NAME
    __main__

DESCRIPTION
    Main program for the Fortune Cookie application.
    Controls the flow of language selection and message display.

FUNCTIONS
    main()
        Execute the main process of the Fortune Cookie application.

        Prompts the user to select a language and then displays a random
        fortune message based on the user's choice.

        Flow summary:
            1. Prompt the user to choose a language (Japanese / English).
            2. Retrieve messages and fortune texts from the corresponding
               language module.
            3. Display the fortune only when the user answers "y"
               to the question "Would you like to open a cookie?"

        Raises:
            KeyError: Raised when a required key is missing from the `MESSAGES`
                dict in the language module.
            Exception: Raised when an unexpected error occurs.

FILE
    c:\users\xxx\documents\python101\fortune_cookie\fortune.py

Result for manager.language_manager:

Help on module manager.language_manager in manager:

NAME
    manager.language_manager - Module for managing messages by language.

DESCRIPTION
    Based on the provided language code (e.g., 'jp', 'en'), this module
    dynamically imports and returns the corresponding message module.

FUNCTIONS
    get_language_module(lang_code)
        Return the message module corresponding to the given language code.

        Based on the provided language code (`lang_code`), dynamically import
        the corresponding language module (`message.language_en` or
        `message.language_jp`).

        If an unsupported language code is provided, the Japanese module
        is returned by default.

        Args:
            lang_code (str): The language code ('en' or 'jp').

        Returns:
            module: The module object corresponding to the given language code.

        Raises:
            SystemExit: Raised to indicate abnormal termination when importing
                the message module fails.

FILE
    c:\users\xxx\documents\python101\fortune_cookie\manager\language_manager.py

Result for message.language_en:

Help on module message.language_en in message:

NAME
    message.language_en - Module for managing English messages.

DESCRIPTION
    This module defines the English messages and fortune texts used
    in the Fortune Cookie application.

DATA
    FORTUNES = ['Great Fortune! A wonderful day awaits you.', 'Fair Fortun...
    MESSAGES = {'app_title': 'Fortune Cookie', 'fortune_prefix': 'Your for...

FILE
    c:\users\xxx\documents\python101\fortune_cookie\message\language_en.py
スポンサーリンク