01 / 20

Docstrings &
Comments

Learn how to write meaningful documentation directly inside your Python code, making it readable, maintainable, and professional.

Python

Why Documentation Matters

Code is read far more often than it is written. Six months from now, you are the stranger reading your own code. Comments and docstrings are your notes to the future: they explain the why behind the what.

Two Tools: Comments vs Docstrings

# Comments
Short notes for developers reading the source code. Ignored by Python at runtime. Start with the # symbol.
"""Docstrings"""
Structured documentation attached to modules, classes, or functions. Accessible at runtime via the __doc__ attribute.

Anatomy of a Documented Function

def calculate_area ( width , height ): Function signature """Calculate the area of a rectangle. Args: width (float): The width in units. height (float): The height in units. Returns: float: The computed area. """ Docstring # Multiply dimensions Inline comment return width * height # Access the docstring at runtime: print(calculate_area.__doc__)

The # Comment: Rules & Best Practices

1
Explain why, not what. The code shows what happens: your comment should say why it happens.
2
Keep them short. One or two lines max. If you need more, consider a docstring or refactoring.
3
Place above the code they describe, on their own line. Inline end-of-line comments are for short clarifications only.
4
Update when code changes. A stale comment is worse than no comment: it actively misleads.

Docstrings: The Formal Standard

A docstring is the first statement inside a module, class, method, or function. Python stores it in the object's __doc__ attribute, making it available to help() and documentation generators.

One-liner
For simple, obvious functions. Fits on a single line inside triple quotes. Example: """Return the square of n."""
Multi-line
Summary line, blank line, then sections like Args, Returns, Raises, and Examples.

Comments vs Docstrings: Key Differences

# Comment """Docstring"""
Syntax # text """text"""
Placement Anywhere in code First statement of module/class/function
Runtime access Stripped by Python Stored in __doc__
Audience Developers reading source Developers + users via help()
Purpose Explain why Explain what and how to use

Popular Docstring Styles

Google Style
Uses Args:, Returns:, Raises: as section headers. Clean and readable.
NumPy/SciPy Style
Uses underlined section headers like Parameters and Returns. Common in data science.
reStructuredText
Uses :param name: and :returns: directives. Default for Sphinx docs.

Step-by-Step: Writing Great Docs

1
Write the function first. Get the logic working before you document it.
2
Add a one-line docstring. Summarize what the function does in a single imperative sentence: "Calculate the total price."
3
Expand if needed. Add Args, Returns, and Raises sections for complex functions.
4
Add comments for tricky logic. Use # comments only where the reason behind a line isn't obvious.
5
Review and prune. Remove any comment that merely restates the code. Keep docs accurate as code evolves.

Example 1: Simple Function

def celsius_to_fahrenheit(temp):
    """Convert a Celsius temperature to Fahrenheit."""
    return temp * 9 / 5 + 32

Example 2: Multi-line Docstring

def find_median(numbers):
    """Return the median of a list of numbers.

    Args:
        numbers (list[float]): Non-empty list
            of numeric values.

    Returns:
        float: The median value.

    Raises:
        ValueError: If the list is empty.
    """
    if not numbers:
        raise ValueError("List is empty")
    sorted_nums = sorted(numbers)
    mid = len(sorted_nums) // 2
    # Average two middle values for even-length lists
    if len(sorted_nums) % 2 == 0:
        return (sorted_nums[mid - 1] + sorted_nums[mid]) / 2
    return sorted_nums[mid]

Example 3: Documenting a Class

class BankAccount:
    """A simple bank account with deposit and withdraw.

    Attributes:
        owner (str): Account holder's name.
        balance (float): Current balance in USD.
    """

    def __init__(self, owner, balance=0.0):
        """Initialize account with owner and optional balance."""
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        """Add amount to balance. Returns new balance."""
        self.balance += amount
        return self.balance

Good vs Bad Comments

✕ Bad
# increment x by 1
x = x + 1

# set name to Alice
name = "Alice"
✓ Good
# Compensate for 0-based index
x = x + 1

# Default for demo mode
name = "Alice"

Common Mistakes to Avoid

✕ Restating Code
Writing # add 1 to count above count += 1 adds zero value. Explain the reason instead.
✕ Stale Comments
Changing logic but leaving the old comment creates misleading documentation that causes bugs.
✕ Missing Docstrings
Public functions without docstrings make your code unusable for anyone relying on help().

Summary: Quick Reference

Comment One-Line Docstring Multi-Line Docstring
Syntax # text """text""" """text\n\nArgs:..."""
Where Any line Simple functions Complex functions/classes
Answers Why? What does it do? What, how, edge cases?
Runtime? No Yes (__doc__) Yes (__doc__)
Tools Source reading help(), IDE tooltips Sphinx, pdoc, mkdocs

Question 1 of 5

What is the primary difference between a comment and a docstring in Python?

Question 2 of 5

What is wrong with the comment in this function?

Question 3 of 5

Where must a docstring be placed for Python to recognize it as documentation?

Question 4 of 5

Which of the following is a well-written inline comment?

Question 5 of 5

Which documentation style is used in the function above?