Search⌘ K

Documentation: Docstrings

Explore the purpose and usage of docstrings in Python to document code components like modules, classes, and functions. Understand how docstrings clarify input, output, and behavior for other developers, enhance maintainability, and integrate with tools like help() and Sphinx. Learn when to add detailed docstrings and the importance of updating documentation as code evolves.

In simple terms, we can say that docstrings are documentation embedded in the source code. A docstring is basically a literal string, placed somewhere in the code to document that part of the logic.

Notice the emphasis on the word documentation. This is important because it's meant to represent explanation, not justification. Docstrings are not comments; they are documentation.

Purpose of docstrings

Docstrings are intended to provide documentation for a particular component (a module, class, method, or function) in the code that will be useful for other developers. The idea is that when other engineers want to use the component we're writing, they'll take a look at the docstring to understand how it's supposed to work, what the expected inputs and outputs are, and so on. For this reason, it is a good practice to add docstrings whenever possible.

Docstrings are also useful for documenting design and architecture decisions. It's probably a good idea to add a docstring to the most important Python modules, functions, and classes in order to hint to the reader how that component fits in the overall architecture.

The ...