Python docstrings are essential for documenting your code, making it more readable and maintainable. They serve as the official documentation for your functions, classes, and modules, and are used by tools like help() and documentation generators like Sphinx. While the basic concept is simple – a multiline string used as the first statement in a code block – several conventions exist regarding format and content. This tutorial will explore the most popular docstring styles.
What are Docstrings?
A docstring (documentation string) is a string literal that occurs as the first statement in a module, function, class, or method definition. It’s written within triple quotes ("""Docstring goes here"""
or '''Docstring goes here'''
). Python makes these strings available via the __doc__
attribute.
def my_function():
"""This is a simple docstring.
It explains what the function does.
"""
print("Hello, world!")
print(my_function.__doc__)
Popular Docstring Formats
Several formats are commonly used for writing docstrings. Here’s an overview of the most prevalent styles:
1. Epytext
Epytext originated with the Epydoc tool, a Python documentation generator. It adopts a Javadoc-like style, using tags like @param
, @return
, and @raise
to specify parameters, return values, and exceptions.
def my_function(param1, param2):
"""This is a javadoc style docstring.
@param param1: Description of the first parameter.
@param param2: Description of the second parameter.
@return: Description of the return value.
@raise KeyError: Raised if a key is not found.
"""
pass
While historically significant, Epytext is less common in modern Python projects.
2. reStructuredText (reST)
reST is the default format used by Sphinx, a powerful documentation generator. It’s a markup language that allows for rich formatting and cross-referencing. It’s a flexible format and can describe complex structures effectively.
def my_function(param1, param2):
"""This is a reST style docstring.
:param param1: Description of the first parameter.
:param param2: Description of the second parameter.
:returns: Description of the return value.
:raises KeyError: Raised if a key is not found.
"""
pass
reST is widely favored due to Sphinx’s popularity and its ability to generate professional-looking documentation. JetBrains PyCharm automatically uses this format when you create a docstring with triple quotes and press Enter.
3. Google Style
The Google style is known for its readability and concise syntax. It’s commonly used in Google’s internal projects and is becoming increasingly popular in the wider Python community. It is easily interpretable by Sphinx with the Napoleon plugin.
def my_function(param1, param2):
"""This is a Google style docstring.
Args:
param1: Description of the first parameter.
param2: Description of the second parameter.
Returns:
Description of the return value.
Raises:
KeyError: Raised if a key is not found.
"""
pass
4. NumPyDoc
NumPyDoc builds upon the Google style and is commonly used in scientific Python projects, particularly those utilizing NumPy and SciPy. It provides a more comprehensive set of sections for documenting complex functions and classes.
def my_function(arg1, arg2):
"""Summary line.
Extended description of function.
Parameters
----------
arg1 : int
Description of arg1
arg2 : str
Description of arg2
Returns
-------
bool
Description of return value
See Also
--------
otherfunc : some related other function
Examples
--------
These are written in doctest format, and should illustrate how to use the function.
>>> a=[1,2,3]
>>> print [x + 3 for x in a]
[4, 5, 6]
"""
return True
Choosing a Style
The "best" style depends on your project’s needs and preferences.
- reST is a solid choice for projects that rely heavily on Sphinx and require rich documentation features.
- Google Style is a good balance between readability and conciseness.
- NumPyDoc is well-suited for scientific and numerical projects.
- Consistency is the most important factor. Choose a style and stick to it throughout your project.
Best Practices
- Write docstrings for all public functions, classes, and modules.
- Keep docstrings concise and informative.
- Use a consistent style throughout your project.
- Keep the summary line of the docstring short and to the point.
- Use clear and descriptive language.
- Include examples whenever possible.
- Update docstrings as your code changes.
By following these guidelines, you can ensure that your Python code is well-documented, easy to understand, and maintainable.