Skip to content

L06 Function Comments

DodaTech 4 min read

title: "Function Comments — Writing Docstrings That Document Interfaces" weight: 6 description: "Learn how to write function comments and docstrings that document interfaces effectively. Master parameter documentation, return types, exceptions, and examples for function-level documentation in any programming language." date: 2026-06-28 lastmod: 2026-06-28 tags: [technical-writing, code-comments]


Function comments, typically written as docstrings, document the interface of a function. They tell developers what the function does, what parameters it takes, what it returns, and what errors it can raise.

In this lesson, you will learn how to write function comments that serve as complete interface documentation.

## What You'll Learn

You will write complete function docstrings with parameters, return types, exceptions, and examples.

## Why It Matters

Functions are the primary unit of code reuse. Good function comments let developers use a function without reading its implementation.

## Real-World Use

DodaTech generates API documentation from Python docstrings. Every public function has a complete docstring that appears in the published docs.

```mermaid
flowchart LR
  A[Function Comment] --> B[Description]
  A --> C[Parameters]
  A --> D[Return Value]
  A --> E[Exceptions]
  A --> F[Examples]
  B --> G[Complete Interface]
  A:::current
  classDef current fill:#f90,color:#fff,stroke:#333,stroke-width:2px

Docstring Structure

Every function docstring should start with a one-sentence description of what the function does. This is the summary line.

Follow with parameter documentation. Each parameter should have name, type, description, and default value.

Document the return value with type and description. If the function does not return anything meaningful, say so.

Document all exceptions the function can raise and under what conditions.

def compress_file(
    input_path: str,
    output_path: str | None = None,
    algorithm: str = "gzip",
    level: int = 6,
) -> CompressResult:
    """Compress a file using the specified algorithm.

    This function reads the input file, compresses it using the chosen
    algorithm and compression level, and writes the result.

    Args:
        input_path: Path to the file to compress. Must exist and be readable.
        output_path: Optional output path. Defaults to input_path with
            the algorithm extension appended.
        algorithm: Compression algorithm. Supported: gzip, bzip2, xz.
        level: Compression level 1-9. Higher values produce smaller output
            but take longer. Default 6 balances speed and size.

    Returns:
        CompressResult with input_size, output_size, ratio, time_ms.

    Raises:
        FileNotFoundError: If input_path does not exist.
        ValueError: If algorithm is not supported.
    """

Examples in Docstrings

Include usage examples in docstrings. Examples show the developer how to call the function and what to expect.

Some docstring formats support runnable examples that can be tested. This ensures examples stay accurate.

Keep examples minimal. Show the typical usage. Do not include examples for every edge case.

def calculate_ratio(input_size: int, output_size: int) -> float:
    """Calculate the compression ratio.

    Ratio = output_size / input_size. A ratio of 0.5 means 50% reduction.

    Args:
        input_size: Original file size in bytes. Must be > 0.
        output_size: Compressed file size in bytes. Must be > 0.

    Returns:
        Compression ratio rounded to 4 decimal places.

    Raises:
        ValueError: If either size is 0 or negative.

    Examples:
        >>> calculate_ratio(1000, 250)
        0.25
        >>> calculate_ratio(1000, 1200)
        1.2
    """

Common Mistakes

1. No Docstring on Public Functions

Functions used by other modules without any documentation.

2. Incomplete Parameters

Some parameters documented, others missing. All parameters must be documented.

3. No Return Value Documentation

Not documenting what the function returns. Developers must read the implementation.

4. No Exception Documentation

Not documenting errors the function can raise. Developers cannot handle them.

5. Vague Descriptions

This function processes data without saying what processing it does or what data it expects.

6. Inconsistent Format

Different docstring styles for different functions in the same project.

7. Examples That Do Not Work

Untested examples that would fail if run. Test docstring examples.

Practice Questions

1. What should every function docstring include?

Description, all parameters, return value, all exceptions, and at least one example.

2. Why include parameter types in docstrings?

Developers need to know what types to pass. Types prevent runtime errors.

3. Why document exceptions?

Developers must know what errors to handle. Undocumented exceptions cause unhandled crashes.

4. Why include examples?

Examples show typical usage faster than reading parameter descriptions.

5. Challenge: Pick three functions from a codebase that lack complete docstrings. Write complete docstrings for each following the structure in this lesson.

FAQ

Should docstrings include default values?

Yes. Document what the default is and what it does.

How do I document *args and **kwargs?

Describe the expected content and usage. Args should be documented as a group if they serve the same purpose.

Should docstrings include type hints if the code has them?

Yes. Docstring types provide documentation that some tools read. Keep both synchronized.

What if a function does not return anything?

Document that it returns None or omit the return section.

Can docstrings be too long?

Yes. Long docstrings are hard to scan. Keep the description focused. Link to external docs for details.

Mini Project

Select a module with three public functions that lack docstrings. Write complete docstrings for all three following the structure from this lesson. Include parameters, return types, exceptions, and examples.

What's Next

Next: Class Comments

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro