Python Best Practices

Chapter 2 · Practice 5 of 5

Write docstrings for public functions, classes and modules

From Style, formatting and linting

Why it matters

Type hints say what a function takes and returns. A docstring says why it exists, what it does with edge cases and what it raises. Editors show docstrings on hover, so they are the first documentation most people read.

Keep them short and useful:

  • The first line is one sentence that says what the function does.
  • Then: what each non-obvious argument means, what is returned, and which exceptions callers should handle.
  • Pick one format (Google or NumPy style) for the project and let Ruff's D rules enforce it.

Do not repeat the type hints in prose. "user_id (int): the user id" adds nothing.

Example

Python
def charge(order: Order, *, idempotency_key: str) -> Receipt:
    """Charge the order total to the customer's saved card.

    Raises:
        PaymentDeclined: the card issuer refused the charge.
        PaymentUnavailable: the provider timed out; safe to retry with the same key.
    """