Docstrings

Module and function docstrings, and help().

A docstring is the first string in a module or function. help() and __doc__ read it. Write one sentence that says what the function returns, not how it loops.

Goal

Add module and function docstrings, then print help text.

Function docstring

def city_label(city):
    """Return a trimmed, title-cased city name."""
    return str(city or "").strip().title()

print(city_label.__doc__)
print(city_label("  nairobi "))

Module docstring

from pathlib import Path

Path("kiosk.py").write_text(
    '''"""Pricing helpers for a Kenya kiosk."""

def line_total(units, price, tax=0.16):
    """Return units * price * (1 + tax), rounded to cents."""
    return round(units * price * (1 + tax), 2)
''',
    encoding="utf-8",
)

import kiosk

print(kiosk.__doc__)
print(kiosk.line_total.__doc__)
help(kiosk.line_total)

help writes to stdout in this editor.

What to write

def format_kes(amount):
    """Return a KES display string for amount."""
    return f"KES {amount:.2f}"

print(format_kes.__doc__)
print(format_kes(23.2))

Say what comes back. Skip restating the code ("rounds and multiplies").

Tip

Triple quotes, one line for small helpers. Add Args: / Returns: only when the function is public and non-obvious.