šŸš€ LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
šŸŽ“ COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
HTML MASTER CLASS /// LEARN TAGS /// BUILD STRUCTURE /// SEMANTIC WEB /// HTML MASTER CLASS /// LEARN TAGS ///

Generating Python Documentation with AI

Using AI to generate genuinely useful documentation — docstrings and comments that explain non-obvious reasoning, not restatements of what well-named code already says.

⚔ Total XP: 0|šŸ’» python XP: 0

Skill Matrix

UNLOCK NODES BY LEARNING NEW TAGS.

System Hub

Core logic.

Quick Quiz //

What's the actual problem with the verbose docstring for calculate_discount() in the first example?


šŸš€ LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
šŸŽ“ COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.

AI-generated documentation has a specific, common failure mode: producing verbose, technically-accurate descriptions of WHAT code does, which well-named identifiers already communicate, while missing the WHY that's actually valuable and non-obvious. This lesson covers steering generation toward the documentation that's genuinely worth having.

1The Default Failure Mode: Verbose Restatement, Not Genuine Documentation

Ask an AI assistant to simply 'add a docstring to this function' without further guidance, and a very common, genuinely unhelpful result follows a predictable pattern: an Args: section restating each parameter's name in slightly more words, a Returns: section restating the return type in prose, and an opening sentence that essentially restates the function's own name as a sentence. For calculate_discount(price: float, percent: float) -> float, a docstring saying 'Calculates the discount' and 'Args: price: The price' adds real, measurable length to the file while adding essentially zero information a reader didn't already have from the function's name and type-hinted signature alone.

This failure mode is worth naming explicitly because it's the *default* behavior many AI assistants fall into without more specific guidance — documentation generation, treated as an open-ended 'describe this code' task, tends toward exhaustive, technically-accurate-but-valueless restatement, precisely because restating visible code accurately is a genuinely achievable, low-risk task for the assistant, even though it doesn't actually serve documentation's real purpose.

This directly echoes this curriculum's own consistently-stated documentation philosophy, established from the very first lessons on writing code: comments and docstrings should explain the WHY — non-obvious reasoning, hidden constraints, workarounds for specific bugs — never the WHAT, which well-named identifiers and type hints already communicate on their own. An AI assistant left to its own defaults will very often produce exactly the WHAT-focused documentation this curriculum has consistently argued against, unless explicitly steered otherwise.

āœ•
—
+
def calculate_discount(price: float, percent: float) -> float:
    """
    Calculates the discount.

    This function takes a price and a percent and calculates
    the discount by multiplying the price by the percent.

    Args:
        price: The price.
        percent: The percent.

    Returns:
        The discount.
    """
    return price * (1 - percent / 100)
# Every sentence here restates what the function's NAME already said
localhost:3000
The Common Failure Mode
Default docstring generation
Verbose restatement of what the code already visibly says — zero new information

2Prompting Specifically for the WHY

The fix is direct and specific: explicitly instruct the AI assistant to include *only* information not already obvious from the function's name, signature, and body — specifically the non-obvious reasoning, hidden business constraints, or workarounds that a reader genuinely could not infer just by reading the code itself. 'Explain WHY we round using ROUND_HALF_UP instead of Python's default banker's rounding, since that's the actual non-obvious business requirement here' directs the assistant toward exactly the kind of information documentation should actually capture.

The resulting docstring — 'Rounds using ROUND_HALF_UP per finance team requirement — Python's default banker's rounding caused discrepancies in reconciliation reports (see JIRA-4821)' — is genuinely valuable in a way the verbose, restating version never could be: no amount of reading the function's code, however carefully, would reveal *why* this specific rounding mode was chosen, or that it traces back to a specific past production issue. That context exists only in institutional memory (or a tracked issue) unless it's explicitly written down — precisely the gap documentation exists to close.

This specific-prompting technique — explicitly constraining an AI assistant toward non-obvious, WHY-focused content rather than accepting its open-ended default behavior — is a direct, practical application of the same context-provision discipline covered throughout this section's earlier lessons: an AI assistant produces dramatically better results when given precise, specific direction about exactly what's actually wanted, rather than a vague, open-ended instruction that leaves it to fall back on generic, low-value defaults.

āœ•
—
+
# Prompt: "Write a docstring for this function, but ONLY include
# information not already obvious from the function name and
# signature -- specifically explain WHY we round using ROUND_HALF_UP
# instead of Python's default banker's rounding, since that's the
# actual non-obvious business requirement here"

def calculate_discount(price: float, percent: float) -> float:
    """Rounds using ROUND_HALF_UP per finance team requirement --
    Python's default banker's rounding caused discrepancies in
    reconciliation reports (see JIRA-4821)."""
    ...
localhost:3000
Explicitly WHY-Focused
"Only include what's not obvious from the code itself"
Produces documentation that captures genuinely hidden, valuable context

3The Same Principle for Inline Comments

This exact same WHY-versus-WHAT distinction applies identically to inline comments, and it's worth prompting an AI assistant for the same specific constraint there too. A comment reading # loop through items and add up the price above a straightforward for loop summing prices adds nothing a reader capable of reading Python doesn't already understand from the code itself — restating visible logic in English prose, exactly the failure mode covered above, just applied to a comment instead of a docstring.

# Intentionally skip items with price=None rather than raising — upstream data occasionally has incomplete entries we tolerate here, attached to the exact same loop with an added None-check, captures something genuinely non-obvious: *why* the code tolerates missing prices rather than raising an error, a deliberate decision reflecting a known, specific characteristic of the upstream data source — information that would otherwise live only in whoever originally wrote that specific check's memory, invisible to every future reader of the code including that same person, months later, having forgotten the specific reasoning.

The practical technique for reliably getting this kind of comment from an AI assistant mirrors the docstring guidance directly: explicitly ask for comments explaining non-obvious reasoning, workarounds, or hidden constraints specifically, and explicitly instruct it to skip commenting on anything a competent reader would understand just from reading the code — converting an open-ended, restate-everything default into a targeted request for exactly the kind of documentation this curriculum has emphasized as genuinely worth writing throughout every prior lesson.

āœ•
—
+
# Weak (restates the obvious): # loop through items and add up the price
for item in items:
    total += item.price

# Valuable (explains non-obvious WHY):
# Intentionally skip items with price=None rather than raising --
# upstream data occasionally has incomplete entries we tolerate here
for item in items:
    if item.price is not None:
        total += item.price
localhost:3000
WHY-Focused Comments
Explains a deliberate, non-obvious decision
Not a narration of code any competent reader would already understand

4Step-by-Step Breakdown

A docstring that says 'this function calculates the total' for a function named calculate_total() adds nothing a reader didn't already know from the function's name alone.

The DEFAULT failure mode: AI generates verbose docstrings restating what well-named code ALREADY communicates -- adding length, not value.

Checkpoint: What's the actual problem with the verbose docstring for calculate_discount() in the first example?

  • →Every sentence just restates what the function's own name and signature already communicate -- it adds length without adding genuinely new information
  • →The docstring is factually inaccurate about what the function does

Prompting SPECIFICALLY for the WHY -- non-obvious reasoning, edge cases, constraints -- produces documentation actually worth having.

Checkpoint: Why does the SECOND docstring (about ROUND_HALF_UP) provide genuine value the first one did not?

  • →It explains a specific, non-obvious business reason (a past reconciliation discrepancy) that a reader could NEVER infer just from reading the code itself
  • →It simply contains more words and technical detail than the first version

The same principle applies to inline comments -- ask specifically for comments explaining non-obvious reasoning, not a line-by-line narration of what the code visibly does.

Documentation explains existing code to humans; AI Test Generation is next, using AI assistance to verify that code actually behaves as documented.

Detect a Real Low-Value Docstring. Finish is_low_value_docstring(): a docstring restating the function's own name adds nothing.

Level Up šŸš€

Advanced cheat sheets, SEO tricks, and interview prep for this topic.

Browser Support

ChromeSupported

Fully supported (via server-side Python execution).

FirefoxSupported

Fully supported (via server-side Python execution).

SafariSupported

Fully supported (via server-side Python execution).

EdgeSupported

Fully supported (via server-side Python execution).

Best Practices

Explicitly instruct AI documentation generation to include only non-obvious information not already clear from the code itself

The default, unconstrained behavior tends toward verbose restatement of what well-named code already communicates -- explicit steering is needed to reliably get genuinely valuable, WHY-focused documentation instead.

Apply the same WHY-not-WHAT constraint to both docstrings and inline comments

This mirrors this curriculum's consistent documentation philosophy throughout -- valuable documentation explains hidden reasoning, constraints, and decisions; it never merely narrates what visible, well-named code already shows.

Frequent Bugs

THE BUG

Accepting AI-generated docstrings and comments without reviewing whether they add genuine, non-obvious information, resulting in a codebase cluttered with verbose documentation that restates what well-named code already communicates.

THE FIX

Explicitly prompt for WHY-focused documentation (non-obvious reasoning, hidden constraints) and review generated documentation to confirm it adds real information beyond what the code itself already shows.

Real-World Examples

Documenting a Non-Obvious Business Rule Correctly

A function contains a specific rounding behavior that traces back to a past production incident, and the team wants this genuinely non-obvious context captured in the docstring rather than a generic restatement of the function's visible logic.

# Effective prompt:
# "Write a docstring for this function. Do NOT restate what's
#  obvious from the function name and signature. DO explain why
#  we use ROUND_HALF_UP specifically -- it relates to a past
#  reconciliation bug (JIRA-4821) that the finance team requires
#  us to avoid repeating."
#
# Result: a docstring capturing genuinely hidden, valuable context
# instead of restating price * (1 - percent/100) in prose

Interview Prep

?Frequently Asked Questions

Pascual Vila

Pascual Vila

Frontend Instructor // Code Syllabus

Common Pitfalls & Errors

The Error //

Accepting AI-generated docstrings and comments that verbosely restate what well-named code already communicates, cluttering the codebase with documentation that adds length without genuine value.

# Low value: restates the obvious """Calculates the discount. Args: price: The price. percent: The percent. """ # High value: explains genuinely non-obvious reasoning """Rounds using ROUND_HALF_UP per finance team requirement -- Python's default banker's rounding caused reconciliation discrepancies (JIRA-4821)."""

The Solution //

Explicitly prompt for documentation that only includes non-obvious information not already clear from the code itself, and review generated output against this standard before accepting it.

Lesson Glossary

[01]WHY vs WHAT documentation

The distinction between explaining non-obvious reasoning behind code (WHY, valuable) versus restating what the code visibly does (WHAT, usually redundant).

Code Preview
// WHY vs WHAT documentation context

[02]Verbose restatement

A common AI documentation failure mode of describing code accurately but redundantly, adding length without new information.

Code Preview
// Verbose restatement context

[03]Non-obvious reasoning

Hidden context, constraints, or decisions behind a piece of code that cannot be inferred by reading the code itself, worth capturing in documentation.

Code Preview
// Non-obvious reasoning context

[04]Steered generation

Explicitly constraining an AI assistant's output (e.g. "only include non-obvious information") to avoid its default, less useful behavior.

Code Preview
// Steered generation context

Continue Learning