docformatter
docformatter is a Python tool that automatically formats docstrings to adhere to PEP 257 conventions, ensuring consistent and readable documentation. It handles various aspects like summary line wrapping, blank lines, and multi-line docstring structure. The library is actively maintained, with frequent releases addressing bug fixes and new features, and its current version is 1.7.7.
Warnings
- breaking Starting with version 1.7.7, `docformatter` dropped official support for Python versions older than 3.9. Users on older Python environments will need to use a previous version of the library.
- gotcha Integrating `docformatter` with complex docstrings, especially those using reStructuredText (reST) or Sphinx-style field lists, can sometimes lead to unexpected formatting or require specific options. The project has had several fixes related to handling Sphinx fields, directives, and wrapping.
- gotcha When used as a `pre-commit` hook, incorrect `rev` or `args` in `.pre-commit-config.yaml` can lead to manifest issues or unexpected behavior. Specifically, older examples might use outdated `rev` values, or miss crucial arguments like `--in-place`.
- gotcha `docformatter`'s `--black` option (introduced in v1.7.0) aims for Black compatibility but may not cover all Black-specific formatting nuances or interactions, as Black primarily focuses on code formatting, not docstrings.
Install
-
pip install docformatter -
pip install "docformatter[tomli]"
Quickstart
import subprocess
import os
# Create a dummy Python file with unformatted docstrings
code_to_format = '''
def my_function(arg1, arg2):
"""This is a very long and unformatted summary line that definitely exceeds the default wrap length of 79 characters.
This is the description. It also needs to be wrapped. It contains details about arg1 and arg2.
:param arg1: The first argument.
:type arg1: int
:param arg2: The second argument.
:type arg2: str
"""
pass
class MyClass:
"""A class with a simple docstring. It needs to be formatted."""
def __init__(self):
pass
'''
file_path = "example_docstrings.py"
with open(file_path, "w") as f:
f.write(code_to_format)
print(f"Original file '{file_path}':\n---\n{code_to_format}---\n")
# Run docformatter to format the file in-place
try:
# Using --recursive (or -r) is good practice for multiple files/directories
# Using --in-place (or -i) makes changes directly to the file
result = subprocess.run(["docformatter", "--in-place", file_path], check=True, capture_output=True, text=True)
if result.stdout:
print(f"docformatter output (stdout):\n{result.stdout}")
if result.stderr:
print(f"docformatter errors (stderr):\n{result.stderr}")
# Read the formatted content
with open(file_path, "r") as f:
formatted_code = f.read()
print(f"Formatted file '{file_path}':\n---\n{formatted_code}---\n")
except subprocess.CalledProcessError as e:
print(f"Error running docformatter: {e}")
print(f"stdout: {e.stdout}")
print(f"stderr: {e.stderr}")
finally:
# Clean up the dummy file
if os.path.exists(file_path):
os.remove(file_path)
print(f"Cleaned up '{file_path}'.")