- 1 1. What is a docstring in Python?
- 2 2. Basic Way to Write docstrings
- 3 3. docstring Styles (Google, NumPy, reStructuredText)
- 4 4. PEP 257 and Best Practices
- 5 5. Testing Using docstrings (doctest)
- 6 6. Practical Example: Documenting Code Using docstrings
- 7 7. Common Mistakes and How to Avoid Them
- 8 8. Conclusion: Efficient Documentation Through docstrings
1. What is a docstring in Python?
In Python, a docstring is a special kind of string used to add explanatory text to code elements such as functions, classes, and modules. Docstrings play a vital role in improving code maintainability and helping other developers understand the code more easily. By using automated documentation tools (e.g., Sphinx), you can leverage docstrings to generate full-fledged documentation as described later.
Location and Format of a docstring
A docstring is placed immediately after the definition of the target function, class, or module, and is typically enclosed within triple double-quotes. The general syntax looks like this:
def function_name(arguments):
"""
Brief description of what the function does.
Arguments:
arg_name (type): Detailed explanation about the argument
Returns:
type: Description of what is returned
"""
passThe docstring can be used by Python’s built-in help() function or shown by editors for inline assistance. As such, it serves as a key part of the code’s documentation.
2. Basic Way to Write docstrings
Python docstrings are used to describe the specifications of functions or classes in a concise and clear manner. The typical format begins with a short explanation of the function’s purpose, followed by descriptions of arguments, return values, and possible errors. Following the official style guide, PEP 257, ensures consistency so that other developers can easily understand the code.
Basic docstring Structures
A one-line docstring is used when only a very short description is needed — typically to briefly state what the function does. For example:
def add(a, b):
"""Return the sum of two numbers."""
return a + bFor more detailed explanations, a multi-line docstring can be used. It describes the function’s behavior, arguments, and return value in detail, using line breaks to improve readability:
def add(a, b):
"""
Add two numbers and return the result.
Arguments:
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
3. docstring Styles (Google, NumPy, reStructuredText)
There are various docstring styles, depending on the project or the tools used. The three widely adopted formats are the Google style, NumPy style, and reStructuredText style.
Google Style
The Google style is characterized by concise and visually easy-to-read formatting. Under section headers such as Args or Returns, arguments and return values are described, making it straightforward to understand the function’s behavior.
def add(a, b):
"""
Return 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 + bNumPy Style
The NumPy style provides a more detailed format, and is widely used in libraries related to scientific computing and data analysis. It uses section headers such as Parameters and Returns to describe arguments and returns in detail.
def add(a, b):
"""
Return 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 + breStructuredText Style
The reStructuredText style is commonly used with documentation generation tools like Sphinx, and is well-suited for complex projects. It enables generating HTML or PDF documentation automatically from the code.
def add(a, b):
"""
Add 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
The official style guide for Python docstrings, PEP 257, provides clear recommendations on how to write docstrings. Following those guidelines helps improve code readability and makes it easier for you and other developers to understand the code.
Key Points of PEP 257
- One-line docstring
For simple functions or methods, a concise one-line description is recommended. - Multi-line docstring
When a detailed description is necessary, use a multi-line docstring. In this case, the first line should be a short summary, followed by a blank line, then a more detailed explanation. - Use of indentation and blank lines
Within thedocstring, use line breaks and indentation to enhance readability. Clearly separate information about arguments and return values.
Best Practices
- Be concise and clear
Thedocstringshould succinctly yet accurately convey what the function or class does. Avoid unnecessary information, while thoroughly describing important parts. - Maintain consistent style
Choose a docstring style (e.g., Google, NumPy, or reStructuredText) that suits your project or team, and apply it consistently across the codebase to enhance readability.
5. Testing Using docstrings (doctest)
Python provides the doctest module, which allows code examples within docstrings to be automatically executed and verified. By doing so, you can ensure that the examples included in docstrings work as expected, improving confidence in your documentation.
Basic Usage of doctest
doctest automatically finds code samples written inside docstrings and checks whether the actual output matches the expected output described in the docstring. By adding a doctest invocation inside an if __name__ == "__main__": block, you can run those checks as follows:
def add(a, b):
"""
Add two numbers and return the result.
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 the example above, doctest will execute the code samples within the docstring and verify if their outputs match what’s documented. If the tests pass, nothing is printed; if they fail, error messages are shown. This helps ensure that the examples in the docstring remain correct over time.
Advantages of Using doctest
- Consistency between code and documentation
By using doctest, you ensure that the sample code in docstrings actually works, keeping documentation in sync with the code. This helps maintain accuracy as the code evolves. - Automated testing
doctest enables automated testing without needing manual test code. Just running doctest ensures that all code examples in docstrings are validated, reducing the likelihood of bugs or mismatches between code and documentation.

6. Practical Example: Documenting Code Using docstrings
By properly using docstrings, Python code readability improves significantly, making it much easier for other developers to understand. Below is an example showing how to add docstrings to classes and methods, and then use Sphinx to automatically generate documentation.
Example of a Class with docstrings
class Calculator:
"""
A simple calculator class.
This class provides basic operations: addition, subtraction, multiplication, and division.
Attributes:
result (int): Holds the calculation result.
"""
def __init__(self):
"""
Constructor for Calculator class.
Initializes result to 0.
"""
self.result = 0
def add(self, a, b):
"""
Add two numbers and return 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.resultIn this example, the class itself has a docstring explaining its overall functionality, and each method (such as __init__ and add) also includes its own docstring. This makes it much easier for users of the class to understand what each method does.
Documentation Generation with Sphinx
By using a tool like Sphinx, you can automatically generate documentation in HTML or PDF formats based on the docstrings. First, install Sphinx and set up the configuration file (conf.py). Then, by running the make html command, you can generate documentation that reflects the docstrings in your Python files.
Install Sphinx with the following command:
pip install sphinxNext, initialize the project by running sphinx-quickstart and adjusting settings as needed. Once ready, Sphinx will automatically include docstring content when building HTML (or PDF) documentation.

7. Common Mistakes and How to Avoid Them
When writing docstrings, beginners often fall into certain common pitfalls. This section highlights those mistakes and explains how to avoid them.
1. Vague or ambiguous explanations
A docstring should be clear and concise. If the description is vague, it fails to communicate the function’s behavior properly. For example:
def add(a, b):
"""Add two numbers."""
return a + bIn this example, the docstring is insufficient — it doesn’t specify what types of numbers are accepted, or what is returned. A better version would be:
def add(a, b):
"""
Add two integers and return the result.
Args:
a (int): The first number.
b (int): The second number.
Returns:
int: The sum of the two numbers.
"""
return a + b2. Inaccurate or missing descriptions for arguments or return values
If argument types or return values are not described correctly, users may misuse the function. Especially for complex functions, it’s important to specify the argument types, their meaning, and what’s returned. For example:
def divide(a, b):
"""Divide two numbers."""
return a / bThis docstring lacks details about arguments and potential error cases. A better approach is:
def divide(a, b):
"""
Divide two numbers and return the result. Raises an error when dividing by zero.
Args:
a (float): Numerator.
b (float): Denominator.
Returns:
float: The result of the division.
Raises:
ZeroDivisionError: If b is zero.
"""
if b == 0:
raise ZeroDivisionError("Cannot divide by zero")
return a / b
8. Conclusion: Efficient Documentation Through docstrings
In this article, we’ve covered the importance of Python docstrings — how to write them, the different styles available, and best practices for maintaining readability and consistency. By following PEP 257 and adopting a unified docstring style, you can produce clean, understandable documentation.
Moreover, you’ve seen how using doctest for testing code examples and a tool like Sphinx for documentation generation can help maintain code quality and workflow efficiency. Proper use of docstrings can enhance code quality and boost development productivity.
Consistent Documentation with PEP 257
PEP 257 is the official guideline for writing Python docstrings. By following it, you can ensure a consistent, readable documentation style. In particular, use one-line docstrings for simple functions, and multi-line docstrings for functions requiring more detail — this helps communicate intent clearly.
Automated Testing of Sample Code via doctest
By using doctest, you can automatically test sample code within docstrings, ensuring that code examples remain valid over time. This helps avoid bugs and keeps documentation reliable.
Automatic Documentation Generation with Sphinx
Using a documentation tool like Sphinx enables you to generate HTML or PDF documentation directly from docstrings. This reduces manual effort and ensures your documentation always reflects the latest code.




