Since docstrings are free-form, it really depends on what you use to parse code to generate API documentation.

I would recommend getting familiar with the Sphinx markup, since it is widely used and is becoming the de-facto standard for documenting Python projects, in part because of the excellent readthedocs.org service. To paraphrase an example from the Sphinx documentation as a Python snippet:

def send_message(sender, recipient, message_body, priority=1) -> int:
   """
   Send a message to a recipient.

   :param str sender: The person sending the message
   :param str recipient: The recipient of the message
   :param str message_body: The body of the message
   :param priority: The priority of the message, can be a number 1-5
   :type priority: integer or None
   :return: the message id
   :rtype: int
   :raises ValueError: if the message_body exceeds 160 characters
   :raises TypeError: if the message_body is not a basestring
   """

This markup supports cross-referencing between documents and more. Note that the Sphinx documentation uses (e.g.) :py:attr: whereas you can just use :attr: when documenting from the source code.

Naturally, there are other tools to document APIs. There's the more classic Doxygen which uses \param commands but those are not specifically designed to document Python code like Sphinx is.

Note that there is a similar question with a similar answer in here...

Answer from anarcat on Stack Overflow
Top answer
1 of 9
316

Since docstrings are free-form, it really depends on what you use to parse code to generate API documentation.

I would recommend getting familiar with the Sphinx markup, since it is widely used and is becoming the de-facto standard for documenting Python projects, in part because of the excellent readthedocs.org service. To paraphrase an example from the Sphinx documentation as a Python snippet:

def send_message(sender, recipient, message_body, priority=1) -> int:
   """
   Send a message to a recipient.

   :param str sender: The person sending the message
   :param str recipient: The recipient of the message
   :param str message_body: The body of the message
   :param priority: The priority of the message, can be a number 1-5
   :type priority: integer or None
   :return: the message id
   :rtype: int
   :raises ValueError: if the message_body exceeds 160 characters
   :raises TypeError: if the message_body is not a basestring
   """

This markup supports cross-referencing between documents and more. Note that the Sphinx documentation uses (e.g.) :py:attr: whereas you can just use :attr: when documenting from the source code.

Naturally, there are other tools to document APIs. There's the more classic Doxygen which uses \param commands but those are not specifically designed to document Python code like Sphinx is.

Note that there is a similar question with a similar answer in here...

2 of 9
131

Based on my experience, the numpy docstring conventions (PEP257 superset) are the most widely-spread followed conventions that are also supported by tools, such as Sphinx.

One example:

Parameters
----------
x : type
    Description of parameter `x`.
🌐
Python.org
discuss.python.org › ideas
Another attempt at docstrings for names and parameters--using "||" - Ideas - Discussions on Python.org
October 15, 2024 - Motivation: For starters I’d like to refer to the very well-written Motivation for PEP-727 for why there should be a change to the status quo, where third-party tools are used to render per-name/parameter documentation embedded in a large docstring written in specific microsyntaxes.
🌐
DataCamp
datacamp.com › tutorial › docstrings-python
Python Docstrings Tutorial : Examples & Format for Pydoc, Numpy, Sphinx Doc Strings | DataCamp
February 14, 2025 - Attributes ---------- arg : str This is where we store arg, ''' def __init__(self, arg, *args, **kwargs): self.arg = arg def cars(self, distance, destination): '''We can't travel distance in vehicles without fuels, so here is the fuels Parameters ---------- distance : int The amount of distance traveled destination : bool Should the fuels refilled to cover the distance? Raises ------ RuntimeError Out of fuel Returns ------- cars A car mileage ''' pass · The above example is more verbose than any other documentation. It is more lengthy and could only be used for the long and detailed documentation. As you learned that docstrings are accessible through the built-in Python __doc__ attribute and the help() function.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-docstrings
Python Docstrings - GeeksforGeeks
September 19, 2025 - Example: This function divides two numbers using Numpydoc-style docstrings. ... def divide(a, b): """ Divide two numbers. Parameters ---------- a : float Dividend. b : float Divisor. Returns ------- float Quotient of division.
🌐
JetBrains
jetbrains.com › help › pycharm › using-docstrings-to-specify-types.html
Specify types with docstrings | PyCharm Documentation
September 1, 2025 - In the list of intention actions that opens, choose Specify return type in docstring.
🌐
Reddit
reddit.com › r/learnpython › is this docstring correct ? should 'args' or 'parameters', can i avoid have empty line with special character?
r/learnpython on Reddit: Is this docstring correct ? should 'Args' or 'Parameters', can I avoid have empty line with special character?
October 5, 2022 -

Hi, can you please give me your feedback about the way I am writing Python docstring ?Mine looks usually like this: https://imgur.com/a/V6QJLJpand in full text (as I cannot insert the image directly):

def getItemsByFolder(folderId):
"""Get all Items from database that belong to a particular folder.

Args:
folderId (str): A valid folder Id that is present in the Items database
Returns:list: A list containing folders folder Items represented as dictionaries"""

  1. Is there a possibility to avoid this empty line above 'Args' ? (with a special character for example)I do not like it because it takes a lot of screen real-estate for nothing it makes functions hard to read.

  2. Is 'Args' or 'Parameters' the correct keyword ?

🌐
Python-sprints
python-sprints.github.io › pandas › guide › pandas_docstring.html
pandas docstring guide — Python documentation
This function simply wraps the `+` operator, and does not do anything interesting, except for illustrating what is the docstring of a very simple function. Parameters ---------- num1 : int First number to add num2 : int Second number to add Returns ------- int The sum of `num1` and `num2` See Also -------- subtract : Subtract one integer from another Examples -------- >>> add(2, 2) 4 >>> add(25, 0) 25 >>> add(10, -10) 0 """ return num1 + num2
Find elsewhere
🌐
Python
peps.python.org › pep-0257
PEP 257 – Docstring Conventions | peps.python.org
The one-line docstring should NOT be a “signature” reiterating the function/method parameters (which can be obtained by introspection).
🌐
Real Python
realpython.com › how-to-write-docstrings-in-python
How to Write Docstrings in Python – Real Python
June 19, 2025 - In this format, Args lists parameters and their descriptions, Returns describes the return value and its type, and Raises (when included) shows exceptions that might be raised by the function. Google-style docstrings shine when you need a detailed, consistent structure—especially if you’re collaborating on large projects or using documentation generators like Sphinx. The NumPy style of docstrings is favored in scientific and data-oriented Python projects.
🌐
Readthedocs
sphinxcontrib-napoleon.readthedocs.io › en › latest › example_google.html
Example Google Style Python Docstrings — napoleon 0.7 documentation
If attribute, parameter, and return ... to be included in the docstring: Args: param1 (int): The first parameter. param2 (str): The second parameter. Returns: bool: The return value. True for success, False otherwise. .. _PEP 484: https://www.python.org/dev/peps/pep-0484/ """ ...
🌐
Readthedocs
sphinx-rtd-tutorial.readthedocs.io › en › latest › docstrings.html
Writing docstrings — Sphinx-RTD-Tutorial documentation
:param uuids: A list of string service UUIDs to be discovered, defaults to None :type uuids: list, optional :return: A list of the discovered :class:`bluepy.blte.Service` objects, which match the provided ``uuids`` :rtype: list On Python 3.x, this returns a dictionary view object, not a list """ self._services = [] if(uuids is not None): for uuid in uuids: try: service = self.getServiceByUUID(uuid) self.services.append(service) except BTLEException: pass else: self._services = super().getServices() return self._services def setNotificationCallback(self, callback): """Set the callback function to be executed when the device sends a notification to the client.
🌐
Programiz
programiz.com › python-programming › docstrings
Python Docstrings (With Examples)
The docstring for a function or method should summarize its behavior and document its arguments and return values. It should also list all the exceptions that can be raised and other optional arguments. def add_binary(a, b): ''' Return the sum of two decimal numbers in binary digits.
🌐
Pandas
pandas.pydata.org › docs › development › contributing_docstring.html
pandas docstring guide — pandas 3.0.2 documentation
On rare occasions reST styles like bold text or italics will be used in docstrings, but is it common to have inline code, which is presented between backticks. The following are considered inline code: The name of a parameter · Python code, a module, function, built-in, type, literal…
🌐
Software Testing Help
softwaretestinghelp.com › home › python › python docstring: documenting and introspecting functions
Python Docstring: Documenting And Introspecting Functions
April 1, 2025 - Example 4: By referencing code from example 3, use the docstring formats Google docstrings, reStructuredText, and Epytext to rewrite the docstrings. ... """Return the sum of ages Sum and return the ages of your son and daughter Args: age1 (int): The age of your son age2 (int): Optional; The age of your daughter ( default is 30) Returns: age (int): The sum of your son and daughter ages. """ ... """Return the sum of ages Sum and return the ages of your son and daughter :param age1: The age of your son :type age1: int :param age2: Optional; The age of your daughter ( default is 30) :type age2: int :returns age: The sum of your son and daughter ages.
🌐
GitHub
github.com › pyinvoke › invoke › issues › 182
Documenting parameters using docstrings · Issue #182 · pyinvoke/invoke
October 1, 2014 - Documenting task parameters like @task(help={'param1': 'Documentation for this parameter.', 'param2': 'Documentation for that parameter.'}) def example(param1, param2): """Documentation for this task.""" pass feels a bit odd and is prett...
Author   pekkaklarck
Top answer
1 of 6
1389

Formats

Python docstrings can be written following several formats as the other posts showed. However the default Sphinx docstring format was not mentioned and is based on reStructuredText (reST). You can get some information about the main formats in this blog post.

Note that the reST is recommended by the PEP 287

There follows the main used formats for docstrings.

- Epytext

Historically a javadoc like style was prevalent, so it was taken as a base for Epydoc (with the called Epytext format) to generate documentation.

Example:

"""
This is a javadoc style.

@param param1: this is a first param
@param param2: this is a second param
@return: this is a description of what is returned
@raise keyError: raises an exception
"""

- reST

Nowadays, the probably more prevalent format is the reStructuredText (reST) format that is used by Sphinx to generate documentation. Note: it is used by default in JetBrains PyCharm (type triple quotes after defining a method and hit enter). It is also used by default as output format in Pyment.

Example:

"""
This is a reST style.

:param param1: this is a first param
:param param2: this is a second param
:returns: this is a description of what is returned
:raises keyError: raises an exception
"""

- Google

Google has their own format that is often used. It also can be interpreted by Sphinx (ie. using Napoleon plugin).

Example:

"""
This is an example of Google style.

Args:
    param1: This is the first param.
    param2: This is a second param.

Returns:
    This is a description of what is returned.

Raises:
    KeyError: Raises an exception.
"""

Even more examples

- Numpydoc

Note that Numpy recommend to follow their own numpydoc based on Google format and usable by Sphinx.

"""
My numpydoc description of a kind
of very exhautive numpydoc format docstring.

Parameters
----------
first : array_like
    the 1st param name `first`
second :
    the 2nd param
third : {'value', 'other'}, optional
    the 3rd param, by default 'value'

Returns
-------
string
    a value in a string

Raises
------
KeyError
    when a key error
OtherError
    when an other error
"""

Converting/Generating

It is possible to use a tool like Pyment to automatically generate docstrings to a Python project not yet documented, or to convert existing docstrings (can be mixing several formats) from a format to an other one.

Note: The examples are taken from the Pyment documentation

2 of 6
354

The Google style guide contains an excellent Python style guide. It includes conventions for readable docstring syntax that offers better guidance than PEP-257. For example:

def square_root(n):
    """Calculate the square root of a number.

    Args:
        n: the number to get the square root of.
    Returns:
        the square root of n.
    Raises:
        TypeError: if n is not a number.
        ValueError: if n is negative.

    """
    pass

I like to extend this to also include type information in the arguments, as described in this Sphinx documentation tutorial. For example:

def add_value(self, value):
    """Add a new value.

       Args:
           value (str): the value to add.
    """
    pass
🌐
Noirlab
datalab.noirlab.edu › docs › manual › DevGuide › DocumentingPythonAPIswithDocstrings › DocumentingPythonAPIswithDocstrings.html
3.2. Documenting Python APIs with Docstrings — Data Lab documentation
January 4, 2026 - Inside a function or method, there should be no blank lines surrounding the docstring: def sum(values): """Sum numbers in an array. Parameters ---------- values : iterable Python iterable whose values are summed.
🌐
Readthedocs
clize.readthedocs.io › en › stable › docstring-reference.html
Customizing the help using the docstring — clize 5.0.2 documentation
Begin a line with :param NAME: and continue with a description for the parameter. You can continue over more lines by indenting the additional lines. $ python docstring.py --help Usage: docstring.py one and-two Arguments: one This documents the parameter called one.
🌐
Readthedocs
numpydoc.readthedocs.io › en › latest › format.html
Style guide — numpydoc v1.11.0rc0.dev0 Manual
Explanation of parameters passed to a generator’s .send() method, formatted as for Parameters, above. Since, like for Yields and Returns, a single object is always passed to the method, this may describe either the single parameter, or positional arguments passed as a tuple. If a docstring includes Receives it must also include Yields.
🌐
Lsst
developer.lsst.io › python › numpydoc.html
Documenting Python APIs with docstrings — LSST DM Developer Guide main documentation
Inside a function or method, there should be no blank lines surrounding the docstring: def sum(values): """Sum numbers in an array. Parameters ---------- values : iterable Python iterable whose values are summed.