Docstrings That Document Themselves: AI Prompts for Python Technical Writing

The Silent Half of Your Codebase

Every Python developer knows the feeling: you've just finished a brilliant function, the logic is flawless, and then... you stare at the blinking cursor, dreading the docstring. It's tedious, repetitive, and easy to postpone. Yet, documentation is the silent half of your codebase—it's what allows your future self and your teammates to actually use your code without reverse-engineering it. According to a study by researchers at Carnegie Mellon University, developers spend up to 58% of their time trying to understand existing code, not writing new code. That's a staggering amount of time that could be saved with better documentation.

This is where AI prompts come in. Large Language Models (LLMs) excel at pattern recognition and language generation, making them perfect for transforming raw code into clear, structured documentation. But a generic "write a docstring" prompt yields generic results. This guide provides a curated collection of 15 advanced prompts, each designed for a specific documentation scenario. You'll learn how to generate Google-style docstrings, create README files from scratch, explain complex algorithms, and even generate user-facing API documentation—all with the help of AI.

Building the Foundation: Core Prompts

1. The All-Purpose Docstring Generator

Task: Generate a comprehensive docstring for a given function, including a description, parameters, returns, and raises sections.

Prompt:

You are an expert Python developer. Generate a Google-style docstring for the following function. The docstring should include:
- A concise description of what the function does.
- An 'Args' section listing each parameter and its type and purpose.
- A 'Returns' section describing the return value and its type.
- A 'Raises' section for any exceptions that are intentionally raised.

Function code:

{code}

Example Result:

Input:

def calculate_compound_interest(principal, rate, years, compounds_per_year=12):
    return principal * (1 + rate/compounds_per_year)**(compounds_per_year*years)

Output:

"""Calculate compound interest.

Args:
    principal (float): The initial amount of money.
    rate (float): The annual interest rate (as a decimal, e.g., 0.05 for 5%).
    years (int): The number of years the money is invested.
    compounds_per_year (int, optional): The number of times interest is compounded per year. Defaults to 12.

Returns:
    float: The future value of the investment.

Raises:
    ValueError: If principal, rate, or years is negative.
"""

Recommendations: This is your bread-and-butter prompt. Use it for any function, but be aware that the AI might hallucinate 'Raises' clauses. Always verify that the exceptions listed actually exist in your code.

2. Class Documentation Specialist

Task: Generate a docstring for a class, including a summary, attributes, and methods overview.

Prompt:

Create a docstring for the following Python class. The docstring should:
- Start with a high-level description of the class's purpose and responsibility.
- Include an 'Attributes' section that lists all instance variables (with types and descriptions).
- Provide a brief description of each public method, including its parameters and return values.

Class code:

{code}

Example Result:

Input:

class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount
        return self.balance

    def withdraw(self, amount):
        if amount > self.balance:
            raise ValueError("Insufficient funds")
        self.balance -= amount
        return self.balance

Output:

"""A simple bank account.

Attributes:
    owner (str): The name of the account holder.
    balance (float): The current balance in the account.

Methods:
    deposit(amount): Adds money to the account.
    withdraw(amount): Removes money from the account, raising an error if insufficient funds.
"""

Recommendations: For larger classes, you may want to break this down by method groups. This prompt works best when the class is well-structured and follows naming conventions.

3. README Architect

Task: Generate a complete README.md file for a Python project.

Prompt:

You are a technical writer. Create a README.md file for the following Python project. The README should include sections:
1. Project title and a short description.
2. Installation instructions (using pip).
3. Usage examples (with code snippets).
4. Configuration options (if any).
5. Contributing guidelines (brief).
6. License information (assume MIT).

Here is the project code:

{code}

Example Result:

Input: (A simple CLI tool for converting temperatures)

# temperature.py
import sys

def celsius_to_fahrenheit(c):
    return (c * 9/5) + 32

if __name__ == "__main__":
    c = float(sys.argv[1])
    print(f"{c}C = {celsius_to_fahrenheit(c)}F")

Output: (A full README.md with badges, usage, etc.)

Recommendations: This prompt can be further refined. Specify the exact sections you need, the target audience (e.g., end-users vs. developers), and the level of detail. Always review the generated README for accuracy, especially the installation and usage commands.

4. Inline Comment Explainer

Task: Add or improve inline comments for a given piece of code.

Prompt:

Add detailed inline comments to the following code. Explain the purpose of each logical block, the role of key variables, and any non-obvious logic. Use the '#' style. Keep comments concise but informative.

Code:

{code}

Example Result:

Input:

def sieve_of_eratosthenes(n):
    prime = [True] * (n+1)
    prime[0] = prime[1] = False
    for p in range(2, int(n**0.5)+1):
        if prime[p]:
            for i in range(p*p, n+1, p):
                prime[i] = False
    return [i for i in range(n+1) if prime[i]]

Output:

def sieve_of_eratosthenes(n):
    # Initialize a list where each index represents whether the number is prime.
    prime = [True] * (n+1)
    # 0 and 1 are not prime numbers.
    prime[0] = prime[1] = False
    # Iterate from 2 to the square root of n.
    for p in range(2, int(n**0.5)+1):
        if prime[p]:
            # Mark all multiples of p as non-prime.
            for i in range(p*p, n+1, p):
                prime[i] = False
    # Return a list of all prime numbers up to n.
    return [i for i in range(n+1) if prime[i]]

Recommendations: Use this when you're dealing with complex algorithms or legacy code that lacks comments. It helps in code review sessions and onboarding new developers.

Leveling Up: Advanced Documentation

5. Type Annotation Generator

Task: Add type annotations to a function or class.

Prompt:

Add type annotations to the following Python code. Use the 'typing' module where necessary. Ensure that the annotations are consistent with the logic of the code.

Code:

{code}

Example Result:

Input:

def process_data(data, options=None):
    result = []
    for item in data:
        if options and 'filter' in options:
            if item[options['filter']]:
                result.append(item)
        else:
            result.append(item)
    return result

Output:

from typing import List, Dict, Any, Optional

def process_data(data: List[Dict[str, Any]], options: Optional[Dict[str, Any]] = None) -> List[Dict[str, Any]]:
    result = []
    for item in data:
        if options and 'filter' in options:
            if item[options['filter']]:
                result.append(item)
        else:
            result.append(item)
    return result

Recommendations: This is a huge time-saver, especially for codebases that are gradually adopting type hints. Always verify the generated annotations with a type checker like mypy.

6. Complex Algorithm Explainer

Task: Describe the algorithm used in a code snippet in plain English.

Prompt:

Explain the algorithm implemented in the following code in plain English. Break it down step by step, and include a brief analysis of its time and space complexity.

Code:

{code}

Example Result:

Input: (A recursive Fibonacci function)

def fib(n):
    if n <= 1:
        return n
    return fib(n-1) + fib(n-2)

Output:

The function 'fib' calculates the nth Fibonacci number using recursion. It follows the definition: each number is the sum of the two preceding ones, starting from 0 and 1. The base case is when n is 0 or 1, returning n itself. For other values, it recursively calls itself with n-1 and n-2 and adds the results. The time complexity is exponential (O(2^n)) due to overlapping subproblems, and the space complexity is O(n) due to the recursion stack.

Recommendations: This is excellent for documentation that explains the why behind the code, not just the what. It's also useful for code reviews and educational purposes.

7. API Reference Generator

Task: Generate API reference documentation for a module or package.

Prompt:

You are an API documentation expert. Generate reference documentation for the following Python module. For each public function and class, provide:
- A description of its purpose.
- Parameters with types and descriptions.
- Return values with types and descriptions.
- An example usage snippet.

Module code:

{code}

Example Result:

Input: (A module with a function read_config)

# config.py
import json

def read_config(path):
    with open(path) as f:
        return json.load(f)

Output: (A markdown document with sections like read_config(path))

Recommendations: This prompt can be integrated with tools like Sphinx to generate HTML documentation. However, always check that the examples are runnable and the descriptions are accurate.

8. Changelog Creator

Task: Generate a changelog entry from a git diff or a set of commit messages.

Prompt:

Based on the following git commit messages, create a changelog entry for version {version}. Group the changes into categories: Added, Changed, Deprecated, Removed, Fixed, Security. Use a professional tone.

Commit messages:

{commits}

Example Result:

Input:

- Fix bug in login form validation
- Add support for token refresh
- Update dependency versions in requirements.txt
- Remove deprecated admin panel
- Improve performance of data processing

Output:

## v2.1.0

### Added
- Support for token refresh.

### Changed
- Updated dependency versions in requirements.txt.
- Improved performance of data processing.

### Fixed
- Bug in login form validation.

### Removed
- Deprecated admin panel.

Recommendations: This prompt is great for maintaining project history. You can combine it with git log to automate the process.

Reaching Expert Level: Context-Aware Prompts

The following prompts are designed for more complex scenarios where context is crucial.

9. Documentation for Legacy Code

Task: Generate documentation for a poorly documented legacy codebase.

Prompt:

You are a code archaeologist. Analyze the following legacy code and generate comprehensive documentation. Include:
- A high-level overview of what the code does.
- Inline comments explaining the logic.
- Identification of any potential bugs or areas for improvement.

Code:

{code}

Example Result: (A detailed analysis of a messy function, with explanations and suggestions)

Recommendations: This is risky because the AI might misinterpret the code. Always test the code after making changes. Use this prompt to get a starting point, not a final documentation.

10. Multi-File Project Documentation

Task: Generate documentation for an entire project with multiple files.

Prompt:

I have a Python project with the following files:
{list of files}

For each file, generate a docstring at the top that describes the file's purpose, key classes, and functions. Also, generate a high-level overview of how the files interact.

Here is the content of each file:
{code}

Example Result: (A set of module docstrings and an architecture overview)

Recommendations: This prompt works well when the project is small. For larger projects, you may need to break it down by module or package.

11. Style-Guide Conformance

Task: Rewrite documentation to conform to a specific style guide (e.g., Google, NumPy, Sphinx).

Prompt:

Rewrite the following docstring to conform to the {style_guide} style guide. Pay attention to section ordering, formatting, and wording.

Docstring:

{docstring}

Example Result: (Converts a Google-style docstring to NumPy-style)

Recommendations: Specify the style guide explicitly. This is useful for projects that adopt a specific standard.

12. Documentation Review and Improvement

Task: Review existing documentation and suggest improvements.

Prompt:

You are a documentation reviewer. Analyze the following docstring and suggest improvements. Consider clarity, completeness, and adherence to best practices. Provide specific rewrite suggestions.

Docstring:

{docstring}

Example Result: (A critique with rewritten sections)

Recommendations: Use this during code reviews to ensure documentation quality. You can also use it to improve your own documentation before merging.

13. User-Facing Documentation Generator

Task: Generate user-facing documentation (like a tutorial or usage guide) from code.

Prompt:

You are a technical writer. Create a user guide for the following Python library. The guide should be written for non-technical users, with step-by-step instructions and examples. Avoid jargon.

Code:

{code}

Example Result: (A friendly guide with screenshots and examples)

Recommendations: This is great for open-source projects. The AI can turn dry code into engaging tutorials.

14. Docstring for Decorators and Context Managers

Task: Generate documentation for decorators and context managers.

Prompt:

Generate a docstring for the following decorator/context manager. Explain its purpose, parameters, and usage. Include an example.

Code:

{code}

Example Result: (A docstring for a @retry decorator)

Recommendations: These constructs are often tricky to document. This prompt helps clarify their behavior.

15. Documentation for Data Processing Pipelines

Task: Document a chain of functions that form a pipeline.

Prompt:

Describe the following data processing pipeline: list each step, what it does, what it inputs, and what it outputs. Also, describe the overall flow.

Pipeline code:

{code}

Example Result: (A step-by-step description of a pipeline)

Recommendations: Useful for data science projects. You can adapt this prompt to generate diagrams using tools like Mermaid.

The Bottom Line

Documentation is not a chore; it's a craft. With the right prompts, AI can become your documentation partner, handling the mundane parts while you focus on the big picture. Start with the basic prompts, refine them for your specific needs, and gradually incorporate the advanced ones. Remember, AI is a tool—the final responsibility for accuracy and clarity lies with you.

If you're looking to deepen your Python skills and learn how to integrate AI into your workflow, consider checking out the courses at asibiont.com. They offer practical, project-based learning that can help you master these techniques. Happy documenting!

← All posts

Comments