Functions
Docstrings
Documenting functions with structured docstring formats
Interview: Expected in production code — tested in code review and documentation interviews
Docstrings are string literals that appear as the first statement in a module, function, class, or method body. They become the __doc__ attribute and are used by help(), IDE tooltips, and documentation generators. Writing clear docstrings is a professional expectation.
Docstring Conventions
- Triple quotes: Always use
"""triple double quotes"""even for single-line docstrings - PEP 257: The official Python style guide for docstrings — defines formatting conventions
- First line: A one-line summary of what the function does — starts with a capital letter, ends with a period
- Multi-line: Summary line, blank line, then detailed description and parameter documentation
Docstring Formats
- Google style: Uses section headers like "Args:", "Returns:", "Raises:" — most popular in modern Python
- Sphinx/reST: Uses
:param name:,:returns:,:raises:— used by Sphinx documentation generator - NumPy: Uses section headers with underlines — preferred in scientific Python
- Epytext: Legacy format similar to JavaDoc — rarely used in modern code
Accessing Docstrings
Use func.__doc__ to access the raw docstring, help(func) for formatted display, or inspect.getdoc(func) for cleaned-up text. Tools like Sphinx and pdoc generate HTML docs from docstrings automatically.
What to Document
- Arguments: Name, type, and description of each parameter
- Return value: Type and description of what is returned
- Exceptions: What exceptions can be raised and under what conditions
- Examples: Doctest-format examples that can be run as tests
- Side effects: File I/O, network calls, mutable argument modifications
Doctest: Executable Documentation
Examples in docstrings can be run as tests using python -m doctest file.py. This ensures documentation stays in sync with code. Format: >>> function_call() followed by expected output.
Use Cases
Generating API documentation with Sphinx, pdoc, or mkdocstrings
IDE tooltips and autocompletion help for developers using your functions
Running doctests to verify that examples in documentation are correct
Code review standards — all public functions should have docstrings
Help system integration — help(func) displays the docstring
Common Mistakes
Writing docstrings that describe HOW (implementation) instead of WHAT (behavior)
Not updating docstrings when function signatures or behavior change
Using single quotes instead of triple double quotes — PEP 257 requires triple double quotes
Missing the blank line between the summary and detailed description in multi-line docstrings
Not documenting exceptions — callers need to know what can go wrong