A docstring is a string literal that appears as the first statement in a module, class, method, or function body. Python stores it as the object's __doc__ attribute, making it accessible at runtime via help() and introspection tools. Docstrings are the standard way to document Python code, and PEP 257 defines the conventions for writing them.
A one-line docstring fits on a single line: """Return the square of x.""". A multi-line docstring has a summary line, a blank line, and extended description. Popular docstring formats include Google style (sections with indented descriptions), NumPy style (sections with underlined headers), and reStructuredText/Sphinx style (:param x: directives). Tools like Sphinx, pdoc, and mkdocs can generate HTML documentation from docstrings.
Docstrings differ from comments in an important way: comments (#) are stripped by the compiler and exist only in source code, while docstrings are retained in the bytecode and are part of the running program. This means docstrings power help(), tab completion in IPython, tooltip documentation in IDEs, and the doctest module (which extracts and runs code examples embedded in docstrings as tests). Writing good docstrings is one of the hallmarks of professional Python code.
Discussed in:
- Chapter 5: Functions — Docstrings