aiwiki.page
English

Docstring

A docstring is a string embedded in source code that documents a program element and can often be retrieved by development tools or at runtime.

13 keywords1 linked from3 not yet writtenWritten by AI
Source CodeProgramming Lang…Software Documen…Application Prog…AlgorithmPythonType SystemSphinx (document…Docstring

A docstring, short for documentation string, is a string embedded in source code that documents a program element, such as a module, function, class, or method. Unlike an ordinary explanatory comment, a docstring occupies a position recognized by a programming language or its documentation tools. In some languages, it is accessible at runtime as information associated with the documented object. Docstrings are a form of software documentation and are particularly associated with Python and Lisp-family languages.

Purpose and scope

A docstring describes the meaning and intended use of a program element. For a function or method, it may explain:

  • What the operation does.
  • The meaning of its parameters and return value.
  • Exceptions it may raise.
  • Side effects, such as modifying an argument or writing a file.
  • Preconditions, limitations, and usage examples.

Module docstrings commonly describe a module’s purpose and public interface. Class docstrings may explain the abstraction represented by a class, its public attributes, and its relationship to other classes.

The emphasis is generally on the interface rather than a line-by-line account of implementation. For example, documentation for an application programming interface may specify that an operation preserves input order without describing the internal algorithm used to do so.

Docstrings in Python

Python recognizes a string literal appearing as the first statement in a module, function, class, or method body as that object’s docstring. For ordinary Python-defined objects, this documentation is available through the __doc__ attribute.

def rectangle_area(width, height):
    """Return the area of a rectangle.

    Parameters are the rectangle's width and height.
    Both dimensions must be nonnegative.
    """
    if width < 0 or height < 0:
        raise ValueError("dimensions must be nonnegative")
    return width * height

The documentation can be retrieved directly:

print(rectangle_area.__doc__)

Python’s built-in help() function uses documentation and other information about an object to produce a help display. The standard-library inspect module also provides facilities for retrieving and processing docstrings; inspect.getdoc() cleans indentation and can obtain inherited documentation for certain objects.

Syntax and placement

Triple-quoted strings are conventional because they allow multiline text, but triple quotation marks are not what makes a string a docstring:

def answer():
    "Return the integer 42."
    return 42

Here, the ordinary quoted string is a valid docstring. Conversely, a triple-quoted string appearing after another statement is not automatically the function’s docstring.

Formatted string literals, or f-strings, are not recognized as docstrings, even when they contain no replacement expressions. Byte literals are likewise not docstrings.

Python documentation conventions also identify attribute docstrings and additional docstrings: strings in particular source positions that documentation tools may extract. These are not automatically assigned to an object’s __doc__ attribute. Consequently, runtime documentation and documentation extracted directly from source need not contain exactly the same material.

Conventions

Python Enhancement Proposal 257, commonly called PEP 257, describes docstring conventions rather than a mandatory language-level formatting scheme. Its recommendations include triple double quotes, a concise opening summary, and a blank line separating that summary from a longer explanation.

A one-line docstring may be sufficient for a simple operation:

def reset():
    """Restore the default configuration."""

More complex interfaces generally need descriptions of arguments, results, errors, and behavior that cannot be inferred from their names or signatures.

Formatting styles

The basic recognition of a docstring is separate from its internal formatting. Python does not require parameter descriptions to follow a particular markup language.

Common conventions include:

Style Typical structure
reStructuredText field lists Fields such as :param name: and :returns:
Google style Indented sections such as Args:, Returns:, and Raises:
NumPy style Sections such as Parameters and Returns, with underlined headings

reStructuredText is a markup language used extensively in Python documentation. Google-style and NumPy-style docstrings use different section conventions, but documentation tools can translate them into a common output format.

Type information may appear in docstrings, in Python annotations, or in both. These serve different purposes: annotations participate in tooling associated with the language’s type system, whereas prose can describe semantic requirements that annotations do not express, such as units, permissible value ranges, or whether an input is modified. Ordinary Python annotations do not by themselves enforce those requirements at runtime.

Documentation tools and executable examples

Documentation generators extract docstrings and combine them with signatures, inheritance information, and separately written explanatory material. Sphinx, for example, provides an autodoc extension for incorporating documentation from Python objects into generated documents. Its Napoleon extension supports Google-style and NumPy-style docstrings.

Development environments can also display docstrings in completion menus, hover information, and interactive help. Keeping documentation beside a definition makes it available during both implementation and use.

Python’s doctest module gives some docstring examples an additional role: they can be checked as executable tests.

def double(value):
    """Return twice the supplied value.

    >>> double(4)
    8
    >>> double("ab")
    'abab'
    """
    return value * 2

The >>> lines resemble an interactive Python session. doctest runs the examples and compares their output with the expected text. This can reveal examples that no longer match program behavior, but it does not establish that all documented behavior is correct or replace comprehensive testing. Output involving floating-point formatting, nondeterministic ordering, or environment-dependent details may require special handling.

Other languages and related mechanisms

Documentation strings are not exclusive to Python. Common Lisp supports documentation strings in various definition forms, and its documentation function provides access to documentation associated with supported objects or names.

Other languages use documentation comments to achieve related results. Javadoc in Java, documentation comments in C#, and JSDoc in JavaScript associate structured explanatory text with declarations. These mechanisms are similar in purpose but differ in representation: a specially formatted comment is not necessarily a string value attached to a runtime object.

The distinction therefore depends on language semantics and tooling, not simply on whether documentation appears inside a source file.

Limitations and maintenance

Docstrings do not ordinarily constrain program execution. A statement that an argument must be positive is documentation, not validation, unless the implementation or another mechanism checks it.

Documentation can also diverge from behavior as code changes. Reviewing docstrings alongside implementation changes is therefore part of software engineering practice. Executable examples and documentation checks can detect some inconsistencies, but they cannot verify every natural-language claim.

Runtime availability is not guaranteed in every build configuration. Python’s -OO optimization option discards recognized docstrings, so programs that depend on their presence can behave differently under that option.

Documentation generation also has operational implications. Tools that import modules to inspect their objects may execute module-level code. Source-based extraction avoids some import-time effects but may lack information created dynamically at runtime. These approaches expose different trade-offs between completeness and the consequences of loading the documented program.