Skip to content

Docstring

In one line

A docstring is a string literal as the first statement in a module, function, or class, used for documentation.

In simple words

A docstring (documentation string) is a string literal that appears as the first statement in a module, function, class, or method. It documents what the code does. By convention, use triple quotes ("""...""").

Docstrings are accessible at runtime via the __doc__ attribute and are used by tools like help(), Sphinx, and IDEs to generate documentation. They are the Pythonic way to document code.

A good docstring describes what the function does, its parameters, return value, and any exceptions it might raise. Follow a style guide like Google, NumPy, or reStructuredText format for consistency.

Example

python
def divide(a, b):
    """Divide a by b and return the result.

    Args:
        a: The numerator.
        b: The denominator (must not be zero).

    Returns:
        The quotient a / b.

    Raises:
        ZeroDivisionError: If b is zero.
    """
    return a / b

print(divide.__doc__)
help(divide)

Docstrings are triple-quoted strings documenting code. Access via __doc__ or help().

Common confusions

  • Confused with: comment

    The difference: A docstring is a string literal (an object) that documents a module/function/class. A comment (# ...) is ignored by the interpreter entirely. Docstrings are accessible at runtime; comments are not.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary