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

Answer from daouzli on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-docstrings
Python Docstrings - GeeksforGeeks
September 19, 2025 - Example 2: This function shows how to use triple double quotes for docstrings. ... def my_func(): """This is a docstring using triple double quotes.""" return None print(my_func.__doc__) ... This is a docstring using triple double quotes. Google style docstrings follow a specific format and are inspired by Google's documentation style guide. They provide a structured way to document Python code, including parameters, return values and descriptions.
🌐
Python
peps.python.org › pep-0257
PEP 257 – Docstring Conventions | peps.python.org
The docstring in this example contains two newline characters and is therefore 3 lines long.
🌐
Sphinx
sphinx-doc.org › en › master › usage › extensions › example_google.html
Example Google Style Python Docstrings — Sphinx documentation
If attribute, parameter, and return types are annotated according to `PEP 484`_, they do not need 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. """ def function_with_pep484_type_annotations(param1: int, param2: str) -> bool: """Example function with PEP 484 type annotations.
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
🌐
Programiz
programiz.com › python-programming › docstrings
Python Docstrings (With Examples)
For example, "I am a single-line comment" ''' I am a multi-line comment! ''' print("Hello World") Note: We use triple quotation marks for multi-line strings. ... As mentioned above, Python docstrings are strings used right after the definition of a function, method, class, or module (like in ...
🌐
GitHub
gist.github.com › redlotus › 3bc387c2591e3e908c9b63b97b11d24e
Google Style Python Docstrings · GitHub
Google Style Python Docstrings · Raw · docstrings.py · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Find elsewhere
🌐
Python-sprints
python-sprints.github.io › pandas › guide › pandas_docstring.html
pandas docstring guide — Python documentation
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 ...
🌐
Noirlab
datalab.noirlab.edu › docs › manual › DevGuide › DocumentingPythonAPIswithDocstrings › DocumentingPythonAPIswithDocstrings.html
3.2. Documenting Python APIs with Docstrings — Data Lab documentation
For example, the description for format references the should_plot parameter: Parameters ---------- should_plot : `bool` Plot the fit if `True`. plot_format : `str`, optional Format of the plot when ``should_plot`` is `True`. We organize Python docstrings into sections that appear in a common order.
🌐
Lsst
developer.lsst.io › python › numpydoc.html
Documenting Python APIs with docstrings — LSST DM Developer Guide main documentation
For example, the description for format references the should_plot parameter: Parameters ---------- should_plot : `bool` Plot the fit if `True`. plot_format : `str`, optional Format of the plot when ``should_plot`` is `True`. We organize Python docstrings into sections that appear in a common order.
🌐
Rutgers
iw3.math.rutgers.edu › solutions › example_google.html
Example Google Style Python Docstrings — Solutions 0.0.1 documentation
Docstring after attribute, with type specified. ... Class methods are similar to regular functions. ... Do not include the self parameter in the Args section. ... True if successful, False otherwise. ... list of str: Properties with both a getter and setter should only be documented in their getter method. If the setter method contains notable behavior, it should be mentioned here. exception example_google.ExampleError(msg, code)[source]
🌐
Google
google.github.io › styleguide › pyguide.html
Google Python Style Guide
The presence of a trailing comma is also used as a hint to our Python code auto-formatter Black or Pyink to direct it to auto-format the container of items to one item per line when the , after the final element is present. Yes: golomb3 = [0, 1, 3] golomb4 = [ 0, 1, 4, 6, ] ... Two blank lines ...
🌐
Readthedocs
sphinx-rtd-tutorial.readthedocs.io › en › latest › docstrings.html
Writing docstrings — Sphinx-RTD-Tutorial documentation
If you are using VS code, the Python Docstring extension can be used to auto-generate a docstring snippet once a function/class has been written.
🌐
DataCamp
datacamp.com › tutorial › docstrings-python
Python Docstrings Tutorial : Examples & Format for Pydoc, Numpy, Sphinx Doc Strings | DataCamp
February 14, 2025 - In Python, you can access a docstring using the __doc__ attribute of the object. For example, you could access the docstring for a function using my_function.__doc__or the docstring for a class using MyClass.__doc__.
🌐
Software Testing Help
softwaretestinghelp.com › home › python › python docstring: documenting and introspecting functions
Python Docstring: Documenting And Introspecting Functions
April 1, 2025 - At a minimum, a Python docstring should give a quick summary of whatever the function is doing. A function’s docstring can be accessed in two ways. Either directly via the function’s __doc__ special attribute or using the built-in help() function which accesses __doc__ behind the hood. Example 1: Access a function’s docstring via the function’s __doc__ special attribute.
🌐
Shefali
learnify.shefali.dev › tutorials › python-docstrings
Python Docstrings | Learnify
This function takes two parameters ... width (float): The width of the rectangle Returns: float: The area of the rectangle Example: calculate_area(5, 3) 15 """ return length * width...
🌐
Python documentation
docs.python.org › 3 › tutorial › controlflow.html
4. More Control Flow Tools — Python 3.14.7 documentation
The first statement of the function body can optionally be a string literal; this string literal is the function’s documentation string, or docstring.
🌐
Reddit
reddit.com › r/learnpython › advice on writing some docstrings
r/learnpython on Reddit: Advice on writing some docstrings
May 6, 2022 -

I need to write docstrings for every method and property in this file:

https://github.com/golemfactory/yapapi/blob/master/yapapi/services/service_runner.py

A couple questions.

Should you write a docstring for an init method? I suppose it depends? This one seems self explanatory. Should I just state what the code does? “ServiceRunner class is initialized with four parameters: job, instance, instance_tasks, and stopped.”

I could explain what each of those do. I actually have some questions about them. “Job” is clearly passed the string “job”, so I don’t understand the later call “job.id” - the string returns an ID?

As for: self._instances: List[Service] = [] - how can you pass an entire statement as an attribute? They convert “Service” to a list but then assign it as an empty list… will the result be the list of services or the empty list?

Just that for now. Please let me know if you understand this a bit better than I do.

Thanks very much

Top answer
1 of 3
4
You can configure sphinx if that's what you are using for documentation to document __init__ method separately, however, the default is to use the documentation for the class to describe that. I don't like the default and usually configure sphinx not to do that, but you need not do the same. If you are going with defaults, then the class documentation may include :ivar : for class fields. You can also include :param <__init__ param>: in that documentation to document parameters supplied to __init__. The other thing: you misinterpreted type annotation to have some procedural semantics. What it means is that self._instance is believed to have a type of list with elements being of type Service (it's actually wrong, because the code doesn't need it to be a list, it just needs to be something that has methods copy() and append(), but this kind of mistake is very typical of Python as of late.
2 of 3
3
When writing docstrings you should adhere to some style. First see if there exists any existing style guides for the project you are working on. If not then pick a style and stick to it. I prefer Google's docstring style https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings Also note that plugins helps a bunch. Whenever I need a docstring I just hit ,cn and it inserts a boilerplate docstring in the current function. These also exists for VScode, pycharm, etc. Just google a bit for your editor. For examples see for instance https://github.com/psf/requests/blob/main/requests/adapters.py
🌐
PythonForBeginners.com
pythonforbeginners.com › home › python docstrings
Python Docstrings - PythonForBeginners.com
August 28, 2020 - Let’s show how an example of a multi-line docstring: def my_function(): """Do nothing, but document it. No, really, it doesn't do anything. """ pass · Let’s see how this would look like when we print it · >>> print my_function.__doc__ Do nothing, but document it. No, really, it doesn't do anything. The following Python file shows the declaration of docstrings within a python source file:
🌐
Stack Abuse
stackabuse.com › python-docstrings
Python Docstrings
August 23, 2023 - Listing 1: Python code with a single-line docstring · class Device: def __init__(self, temp=0.0): "Initialize the Device object with the given temperature value." self.set_temperature(temp) return · In order to write a docstring correctly follow a number of conventions.