Appearance
What are the most common Python docstring formats?
There are several common formats for Python docstrings. Unlike comments, docstrings are string literals that appear as the first statement in a module, function, class, or method definition. They document the code and can be accessed programmatically.
- The "one-liner" format, which is a single line of text that briefly describes the function or class. Example:
Common one-line docstring format in Python
python
def my_function():
"""This function does something."""- The "Google" format, which uses clear section headers to organize parameters and return values. Example:
Common multi-line docstring format in Python
python
def my_function(arg1, arg2):
"""
This function does something.
Args:
arg1: The first argument.
arg2: The second argument.
Returns:
The result of the function.
"""
<div class="alert alert-info flex not-prose">Watch a video course Python - The Practical Guide
</div>
- The "reStructuredText" format, which is a markup language that is similar to epytext, but is more widely used in Python documentation. Example:
A Python docstring with reStructuredText format
python
def my_function(arg1, arg2):
"""
This function does something.
:param arg1: The first argument.
:param arg2: The second argument.
:return: The result of the function.
"""- The "NumPy" format
NumPy format for docstrings in Python
python
def my_function(arg1, arg2):
"""
This function does something.
Parameters
----------
arg1 : int
The first argument.
arg2 : int
The second argument.
Returns
-------
int
The result of the function.
"""It's worth noting that the Google style is widely used across the broader Python ecosystem, while the NumPy style is standard in scientific and data science communities. PEP 257 provides the official guidelines for Python docstrings, recommending that teams choose one style and apply it consistently. You can access a docstring programmatically using the __doc__ attribute or the built-in help() function.