A docstring is a string literal that appears as the first statement in a Python function, class, or module. It serves as the function's built-in documentation, accessible at runtime through the help function and the doc attribute, and it is the primary input for documentation generators like Sphinx that produce searchable API references from annotated source code. Where the article on function annotations in Python covered how to declare parameter and return types, docstrings cover the "why" and "what": what the function does, what each parameter means in human terms, what the return value represents, and what side effects the caller should anticipate.
Unlike comments, which start with a hash mark and are discarded by the parser, docstrings survive into the running program. The help function reads them and displays them in the interactive interpreter. The doc attribute makes them accessible to any code that wants to introspect a function. This runtime availability is what makes docstrings more than just comments; they are part of the function's metadata, stored alongside its name, annotations, and closure variables.
Docstring syntax and PEP 257
PEP 257, the official Python enhancement proposal for docstring conventions, specifies that docstrings should use triple double quotes even for single-line docstrings. The closing quotes should be on a line by themselves for multi-line docstrings. The first line should be a concise summary ending with a period, followed by a blank line, followed by a more detailed description:
def calculate_total(price, tax_rate):
"""Return the total cost including tax.
Multiplies the price by one plus the tax rate and returns the
result rounded to two decimal places. The tax rate should be
expressed as a decimal, where 0.08 represents eight percent.
"""
return round(price * (1 + tax_rate), 2)The single-line summary appears when help() lists available functions. The detailed description appears when the user requests help on a specific function. Keeping the summary short and the details separated by a blank line ensures that both contexts, quick scanning and deep reading, are well served.
For single-line docstrings, the closing quotes can stay on the same line if the entire docstring fits on one line. This is common for very simple functions where the one-line summary is sufficient documentation. The closing quotes should still be on their own line if the docstring spans multiple lines, even if the summary itself is only one line.
Documenting parameters and return values
The most common docstring convention in modern Python is the Google style, which uses section headers like Args and Returns. This style is readable in plain text, which is how docstrings are most often consumed, through help() in a terminal or by reading source code directly:
def connect(host, port=5432, timeout=30):
"""Open a connection to a database server.
Args:
host: The server hostname or IP address.
port: The port number. Defaults to 5432.
timeout: Connection timeout in seconds. Defaults to 30.
Returns:
A Connection object, or None on failure.
"""Each parameter gets its own line with a name, a colon, and a description. Indentation after a parameter line indicates a continuation of that parameter's description. The Returns section describes the return value, and the Raises section lists any exceptions the function may raise. This structured format makes docstrings scannable for both humans and documentation generators.
The NumPy style and the Sphinx ReStructuredText style are also common, each with slightly different syntax for marking sections. The choice of style matters less than consistency within a project. Pick one style and apply it to every function. A codebase where half the functions use Google style and half use NumPy style is harder to read than one where every function uses the same conventions, even if those conventions are not your personal preference.
What to include and what to leave out
A docstring should describe what the function does, not how it does it. The implementation details, the specific algorithm, the internal variable names, belong in comments within the function body, not in the docstring. The docstring is a contract between the function and its callers, and the implementation may change while the contract stays the same.
Document preconditions that the caller must satisfy, such as "the list must be sorted in ascending order" or "all elements must be non-negative." Document postconditions that the caller can rely on, such as "the returned list is a new list and does not share structure with the input." Document side effects that are not obvious from the return value, such as "writes a log entry to the configured log file" or "modifies the input dictionary in place."
For functions that accept or return complex data structures, describe the shape and meaning of the structure. A parameter documented as "a dictionary mapping user IDs to lists of permissions" is far more helpful than "a dict." The function annotations article covered how type hints express the shape of data; docstrings express the meaning.
Accessing docstrings at runtime
Every function object has a doc attribute that holds its docstring as a string, or None if no docstring was defined. The built-in help function displays this attribute in a formatted way:
print(calculate_total.__doc__)
# Prints the docstring
help(calculate_total)
# Displays the docstring with formatting in the interactive interpreterThe help function is available in the Python REPL, and it is how users of your code explore it interactively. Writing good docstrings is how you ensure that the output of help(your_function) is useful rather than an empty message. The doc attribute is also used by documentation generators that produce HTML or PDF documentation from source code, and by IDE features that display popup documentation when hovering over a function name.
Docstrings as a professional habit
Writing docstrings takes time, and on a tight deadline it is tempting to skip them. But the time you spend writing a docstring is usually less than the time you will spend re-reading your own code months later trying to remember what a parameter meant or what a return value represented. Docstrings are an investment in your future self and in anyone else who needs to use or maintain your code.
A function without a docstring is like a tool without a label. You can figure out what it does by reading the source code, but reading source code is the slowest way to understand a function's purpose. A one-line docstring that says "Return the median of a list of numbers, ignoring None values" is more valuable than a perfectly implemented algorithm with no documentation at all, because the docstring tells the caller what to expect without forcing them to reverse-engineer the implementation. Combined with the clear naming and structure from learning to define and call Python functions, a good docstring completes the picture of what a function does and how to use it correctly.
Rune AI
Key Insights
- A docstring is a triple-quoted string as the first statement in a function, class, or module.
- Use triple double quotes and write a concise summary on the first line, followed by a blank line and details.
- The help() function displays docstrings, and documentation generators like Sphinx extract them automatically.
- Choose a consistent style (Google, NumPy, or Sphinx) and apply it across your entire project.
- Document what the function does, not how it does it; the implementation may change, but the contract stays.
Frequently Asked Questions
What is a docstring in Python?
How is a docstring different from a regular comment?
What style should I use for Python docstrings?
Conclusion
Docstrings are the primary mechanism for documenting Python functions, and writing them well is a habit that separates professional code from disposable scripts. A good docstring explains what the function does, what each parameter means, what the return value represents, and what side effects the caller should expect. The time you invest in docstrings is repaid every time you or someone else reads your code months later.
More in this topic
Define and Call Python Functions
Learn the exact syntax for defining and calling Python functions with the def keyword, including naming rules, the function body, and how the call stack works.
Python Function Parameters and Arguments
Learn the difference between parameters and arguments, how to pass values by position and by keyword, and the rules for default parameter values.
Python Functions Explained
Learn what Python functions are, why they matter for organizing code, and how they form the foundation of non-trivial programs.