docformatter

1.7.7 · active · verified Sat Apr 11

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

Install

Quickstart

This quickstart demonstrates how to use `docformatter` programmatically via `subprocess` to format a Python file's docstrings. It creates a temporary file, runs `docformatter --in-place` on it, and then prints the formatted content before cleaning up.

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}'.")

view raw JSON →