Introduction
PEP 257, short for Python Enhancement Proposal 257, is the style guide for writing docstrings in Python. Docstrings are string literals that appear right after the definition of a function, method, class, or module, and they serve as the official documentation for that segment of code. Adhering to PEP 257 ensures that docstrings are consistent, clear, and useful. This article provides a detailed overview of PEP 257, outlining its key recommendations and offering examples.
What Are Docstrings?
Docstrings, or documentation strings, are a way of embedding documentation directly in the code. They provide a convenient way for developers to understand the purpose and usage of different code components without needing to refer to external documentation. Docstrings are accessible through the built-in help()
function and various documentation generation tools.
General Conventions
PEP 257 outlines several general conventions for writing docstrings:
Triple Quotes:
- Use triple double quotes (
"""
) for docstrings, even for one-liners.
def my_function():
"""Do nothing and return."""
pass
Placement:
- Place the docstring immediately below the function, method, class, or module header.
def my_function():
"""Do nothing and return."""
pass
Content:
- Docstrings should be written in a way that makes it clear what the function, method, class, or module does. They should also mention any important information about parameters, return values, exceptions raised, and other relevant details.
One-liner Docstrings
For very simple functions or methods, a one-liner docstring can suffice. These should be concise and fit on a single line.
Format:
- Use a single line, ending with a period.
def my_function():
"""Do nothing and return."""
pass
No Blank Line:
- Do not include a blank line before or after the one-liner docstring.
def my_function():
"""Do nothing and return."""
pass
Multi-line Docstrings
For more complex functions, methods, classes, or modules, use multi-line docstrings. These should provide a clear description followed by any necessary details.
Summary Line:
- Start with a brief summary of the object’s purpose.
def my_function(param1, param2):
"""Calculate the sum of param1 and param2.
```
Description:
- Follow the summary line with a more detailed description, if necessary.
def my_function(param1, param2):
"""Calculate the sum of param1 and param2.
This function takes two parameters and returns their sum. If either parameter
is not a number, a TypeError is raised.
```
Blank Line:
- Include a blank line after the summary line when the docstring spans multiple lines.
def my_function(param1, param2):
"""Calculate the sum of param1 and param2.
This function takes two parameters and returns their sum. If either parameter
is not a number, a TypeError is raised.
```
Indentation:
- Maintain the same indentation level for all lines in the docstring.
def my_function(param1, param2):
"""Calculate the sum of param1 and param2.
This function takes two parameters and returns their sum. If either parameter
is not a number, a TypeError is raised.
```
Describing Parameters and Return Values
For functions and methods that accept multiple parameters or return values, it is important to document these explicitly:
Parameters:
- List each parameter on a new line, along with its expected type and a brief description.
def my_function(param1, param2):
"""Calculate the sum of param1 and param2.
Args:
param1 (int): The first parameter.
param2 (int): The second parameter.
Returns:
int: The sum of param1 and param2.
```
Return Value:
- Describe the return value, its type, and any relevant details.
def my_function(param1, param2):
"""Calculate the sum of param1 and param2.
Args:
param1 (int): The first parameter.
param2 (int): The second parameter.
Returns:
int: The sum of param1 and param2.
```
Exceptions:
- Mention any exceptions that the function or method might raise.
def my_function(param1, param2):
"""Calculate the sum of param1 and param2.
Args:
param1 (int): The first parameter.
param2 (int): The second parameter.
Returns:
int: The sum of param1 and param2.
Raises:
TypeError: If either param1 or param2 is not an int.
```
Class Docstrings
For classes, the docstring should describe the class’s purpose and provide an overview of its methods and attributes:
Class Docstring:
- Start with a brief summary of the class’s purpose.
class MyClass:
"""A simple example class.
This class demonstrates the use of docstrings in a class context.
"""
def method_one(self):
"""Perform an action."""
pass
def method_two(self):
"""Perform another action."""
pass
Attributes and Methods::
- Include information about the class attributes and methods.
class MyClass:
"""A simple example class.
This class demonstrates the use of docstrings in a class context.
Attributes:
attribute1 (str): Description of attribute1.
attribute2 (int): Description of attribute2.
"""
def __init__(self, attribute1, attribute2):
"""Initialize the class with attribute1 and attribute2.
Args:
attribute1 (str): Description of attribute1.
attribute2 (int): Description of attribute2.
"""
self.attribute1 = attribute1
self.attribute2 = attribute2
def method_one(self):
"""Perform an action."""
pass
def method_two(self):
"""Perform another action."""
pass
Special Methods
For special methods (dunder methods), provide a brief description of their purpose:
Special Methods:
- Use a concise one-liner or a detailed multi-line docstring as needed.
class MyClass:
def __init__(self, value):
"""Initialize the instance with a value."""
self.value = value
def __str__(self):
"""Return the string representation of the instance."""
return f"MyClass with value {self.value}"
Module Docstrings
For modules, the docstring should provide an overview of the module’s purpose and contents:
Module Docstring:
- Place the docstring at the top of the module.
"""
This module provides utilities for string manipulation.
It includes functions for reversing strings, converting case, and more.
"""
def reverse_string(s):
"""Reverse the given string."""
return s[::-1]
def to_uppercase(s):
"""Convert the given string to uppercase."""
return s.upper()
Summary
PEP 257 provides essential guidelines for writing docstrings in Python, promoting clarity and consistency in code documentation. By following these conventions, developers can create documentation that is easy to read, understand, and maintain. Properly documented code not only helps the original authors but also aids future maintainers and users in grasping the functionality and usage of different code components.
Incorporating PEP 257 guidelines into your coding practice ensures that your Python code is well-documented and accessible, contributing to a more robust and professional development environment.