Home

docstrings

Docstrings are string literals used to document modules, classes, methods, and functions. They are written as part of the source code and are intended to describe what the object does, its parameters, return values, and any side effects.

In Python, a docstring is defined as the first statement in the object’s body. It is assigned

Docstrings typically follow conventions such as PEP 257 and can be formatted in various styles (reStructuredText,

Example:

def add(a, b):

"""Return the sum of a and b.

Parameters:

a: first addend

b: second addend

Returns:

The sum of a and b

"""

return a + b

Other languages use documentation comments rather than docstrings. For example, Java uses JavaDoc, and C# uses

Docstrings support automated documentation generation (Sphinx, pydoc) and runtime introspection. They help developers understand code without

Best practices include providing a concise summary, detailing parameters and return values, and avoiding duplication with

to
the
object's
__doc__
attribute
and
is
accessible
at
runtime
via
the
help()
function
or
by
reading
__doc__
directly.
Google
style,
NumPy
style).
The
choice
of
format
affects
readability
and
tooling,
not
runtime
behavior.
XML
documentation
comments.
These
serve
similar
purposes
but
differ
in
syntax
and
tooling.
reading
implementation
details
and
assist
when
building
external
APIs
or
libraries.
code.
Keep
docstrings
up
to
date
as
code
evolves.