- 1 1. What is a docstring in Python?
- 2 3. Docstring Styles (Google, NumPy, and reStructuredText)
- 3 4. PEP 257 and Best Practices
- 4 5. Testing with Docstrings Using doctest
- 5 6. Practical Example: Documenting Code with docstring
- 6 7. Common Mistakes and How to Avoid Them
- 7 8. Summary: Efficient Documentation with docstring
1. What is a docstring
in Python?
In Python, a docstring
is a special kind of string used to add documentation to functions, classes, modules, and other code components. It plays a crucial role in improving code maintainability and making it easier for other developers to understand the code. Moreover, docstrings can be used to generate documentation automatically with tools like Sphinx, which we’ll cover later.
Location and Syntax of a Docstring
A docstring
is placed immediately after the definition of a function, class, or module and is typically enclosed in triple double quotes. The following is a standard example:
def function_name(args):
"""
A brief explanation of what the function does.
Args:
argument_name (type): A detailed explanation of the argument.
Returns:
type: Description of the return value.
"""
pass
docstring
s can be accessed via Python’s built-in help()
function or displayed by code editors to assist developers. They serve as an important part of code documentation.
3. Docstring Styles (Google, NumPy, and reStructuredText)
There are various docstring
styles depending on the project or documentation tools being used. The most common ones are the Google style, NumPy style, and reStructuredText style.
Google Style
The Google style is known for its simplicity and visual clarity. Arguments and return values are organized under sections like Args
and Returns
, making the function’s behavior easy to understand at a glance.
def add(a, b):
"""
Returns the sum of two numbers.
Args:
a (int): The first number to add.
b (int): The second number to add.
Returns:
int: The sum of the two numbers.
"""
return a + b
NumPy Style
The NumPy style is designed for more detailed documentation and is widely used in scientific and data analysis libraries. It uses section headers like Parameters
and Returns
to describe inputs and outputs thoroughly.
def add(a, b):
"""
Returns the sum of two numbers.
Parameters
----------
a : int
The first number to add
b : int
The second number to add
Returns
-------
int
The sum of the two numbers
"""
return a + b
reStructuredText Style
The reStructuredText (reST) style is commonly used with Sphinx, a popular documentation generator. It is especially suited for complex projects. Sphinx can convert docstrings in this style into HTML or PDF documentation automatically.
def add(a, b):
"""
Adds two numbers.
:param a: The first number to add
:type a: int
:param b: The second number to add
:type b: int
:return: The sum of the two numbers
:rtype: int
"""
return a + b

4. PEP 257 and Best Practices
PEP 257 is Python’s official style guide for writing docstrings
. It outlines clear guidelines to improve code readability and help both you and other developers understand the code more easily.
Key Points of PEP 257
- One-line Docstrings
Use a single line to concisely describe simple functions or methods. - Multi-line Docstrings
For more complex behavior, use multi-line docstrings. Start with a short summary, followed by a blank line, and then provide detailed explanations. - Use of Indentation and Line Breaks
Improve readability using indentation and line breaks. Clearly separate sections such as arguments and return values for better structure.
Best Practices
- Clear and Concise Descriptions
Yourdocstring
should clearly state what the function or class does. Avoid unnecessary information, but explain the important parts thoroughly. - Consistent Style
Maintain a consistent docstring style throughout your project. Choose a format like Google, NumPy, or reStructuredText that best suits your team or project.
5. Testing with Docstrings Using doctest
Python includes a module called doctest
that allows you to test whether the examples in your docstrings
work as expected. By using this feature, you can automatically verify that your documentation examples are correct, which increases trust and reliability in your code. With doctest
, you can test documented examples with minimal effort.
Basic Usage of doctest
doctest
automatically detects code examples in docstrings
and checks whether their output matches the documented result. You can run doctest
by adding it to a block like if __name__ == "__main__":
, as shown below:
def add(a, b):
"""
Returns the sum of two numbers.
Args:
a (int): The first number
b (int): The second number
Returns:
int: The sum of the two numbers
Example:
>>> add(2, 3)
5
>>> add(0, 0)
0
"""
return a + b
if __name__ == "__main__":
import doctest
doctest.testmod()
In this example, doctest
runs the sample code inside the docstring
and compares the actual output to the expected result. If the output matches, nothing is printed; otherwise, an error message is displayed. This helps ensure that all your examples remain accurate and up-to-date.
Benefits of Using doctest
- Consistency Between Code and Documentation
Withdoctest
, you can ensure that the sample code in yourdocstrings
actually works. This keeps the documentation aligned with the current state of your code. - Automated Testing
doctest
allows you to automate the testing process. There’s no need to manually test your examples—just rundoctest
and all the embedded examples are validated automatically, reducing the risk of errors.

6. Practical Example: Documenting Code with docstring
Using docstrings
in real-world projects greatly improves code readability and makes it easier for other developers to understand and use your code. In this section, we’ll walk through how to add meaningful docstrings
to classes and functions, and how to generate documentation automatically using Sphinx.
Docstring Example for a Class
It is recommended to add docstrings
not only to functions but also to classes and their methods. A class-level docstring
briefly explains what the class does, while each method’s docstring
describes its specific behavior.
class Calculator:
"""
A simple calculator class.
This class provides basic arithmetic operations such as
addition, subtraction, multiplication, and division.
Attributes:
result (int): A variable to store the calculation result.
"""
def __init__(self):
"""
Initializes the Calculator instance.
Sets the initial result to 0.
"""
self.result = 0
def add(self, a, b):
"""
Adds two numbers and returns the result.
Args:
a (int): The first number
b (int): The second number
Returns:
int: The sum of the two numbers
"""
self.result = a + b
return self.result
This example shows a class-level docstring
as well as separate docstrings
for the __init__
constructor and the add
method. This helps users of the class understand its purpose and how to use each method correctly.
Generating Documentation with Sphinx
With Sphinx, you can automatically generate HTML or PDF documentation from docstrings
. First, install Sphinx and configure it for your project using the conf.py
settings file. Then, simply run the make html
command to generate the docs from your Python code.
To install Sphinx, use the following command:
pip install sphinx
Next, run the sphinx-quickstart
command to set up your documentation project and customize the configuration as needed. Sphinx will then extract the docstrings
from your Python files and turn them into well-formatted documentation automatically.

7. Common Mistakes and How to Avoid Them
When writing docstrings
, beginners often fall into common pitfalls. This section highlights typical mistakes and provides guidance on how to avoid them.
1. Vague Descriptions
docstrings
should be clear and concise. Vague descriptions can confuse readers and fail to communicate the function’s true purpose. For example, the following docstring
is insufficient:
def add(a, b):
"""Adds two numbers."""
return a + b
This example lacks information about the arguments and return value. It’s unclear what data types are expected or what the function actually returns. A better version would be:
def add(a, b):
"""
Adds two integers and returns the result.
Args:
a (int): The first number
b (int): The second number
Returns:
int: The sum of the two numbers
"""
return a + b
2. Inaccurate or Missing Details for Arguments and Return Values
If the docstring
doesn’t clearly describe the function’s parameters and return values, it can be difficult for users to know how to use it properly. This is especially true for more complex functions. Here’s a poor example:
def divide(a, b):
"""Divides two numbers."""
return a / b
This version omits important details such as parameter types and possible exceptions. Here’s a more complete and useful version:
def divide(a, b):
"""
Divides two numbers and returns the result. Raises ZeroDivisionError if dividing by zero.
Args:
a (float): The dividend
b (float): The divisor
Returns:
float: The result of the division
Raises:
ZeroDivisionError: If division by zero is attempted
"""
if b == 0:
raise ZeroDivisionError("Cannot divide by zero")
return a / b
Providing thorough and accurate docstrings
like this helps ensure that users understand how to use your code correctly and safely.

8. Summary: Efficient Documentation with docstring
This article has covered the importance of Python docstrings
, how to write them, various formatting styles, and best practices. docstrings
play a key role in enhancing code readability and maintainability. Following the PEP 257 guidelines ensures a consistent documentation style throughout your project.
We also explored how to leverage doctest
for validating sample code and how to use Sphinx for automatic documentation generation. These tools help improve code quality and streamline the development process.
Consistent Documentation with PEP 257
PEP 257 is the official style guide for Python docstrings
. By following its recommendations, you can create clean, consistent, and easy-to-read documentation. Using concise one-line docstrings
for simple functions and multi-line docstrings
for more complex ones helps communicate the intent of your code effectively.
Testing Examples with doctest
Using doctest
allows you to automatically test the examples written in your docstrings
. This ensures that your documentation stays accurate and synchronized with the actual behavior of your code, helping to prevent bugs and misunderstandings.
Auto-Generating Documentation with Sphinx
With documentation tools like Sphinx, you can generate HTML and PDF files directly from your docstrings
. This eliminates the need for manual documentation and ensures that your docs are always up-to-date with the latest code.