Formats docstrings to follow PEP 257 conventions with support for various docstring styles and Black formatter compatibility
npx @tessl/cli install tessl/pypi-docformatter@1.7.00
# Docformatter
1
2
A comprehensive Python docstring formatter that automatically formats docstrings to follow PEP 257 conventions. Docformatter handles multi-line docstring formatting, triple quote consistency, blank line management, and trailing whitespace removal while maintaining compatibility with Black formatter when using the --black option.
3
4
## Package Information
5
6
- **Package Name**: docformatter
7
- **Language**: Python
8
- **Installation**: `pip install docformatter`
9
- **Optional Installation**: `pip install docformatter[tomli]` (for Python < 3.11 with pyproject.toml support)
10
11
## Core Imports
12
13
```python
14
import docformatter
15
```
16
17
For programmatic usage:
18
19
```python
20
from docformatter import Formatter, Configurater, FormatResult
21
```
22
23
Access to utility functions:
24
25
```python
26
from docformatter import (
27
find_shortest_indentation,
28
normalize_summary,
29
split_summary_and_description,
30
# And other string/syntax functions
31
)
32
```
33
34
## Basic Usage
35
36
### Command-Line Usage
37
38
```python
39
# Format files in-place
40
docformatter --in-place file.py
41
42
# Format recursively with Black compatibility
43
docformatter --black --in-place --recursive .
44
45
# Check formatting without making changes
46
docformatter --check --diff file.py
47
48
# Format with custom line length
49
docformatter --wrap-summaries 88 --wrap-descriptions 88 file.py
50
```
51
52
### Programmatic Usage
53
54
```python
55
import sys
56
from docformatter import Formatter, Configurater
57
58
# Configure docformatter
59
args = ['--in-place', 'example.py']
60
configurator = Configurater(args)
61
configurator.do_parse_arguments()
62
63
# Create formatter instance
64
formatter = Formatter(
65
configurator.args,
66
stderror=sys.stderr,
67
stdin=sys.stdin,
68
stdout=sys.stdout
69
)
70
71
# Format files
72
result = formatter.do_format_files()
73
print(f"Formatting completed with exit code: {result}")
74
```
75
76
## Architecture
77
78
Docformatter uses a modular architecture with distinct responsibilities:
79
80
- **Formatter**: Core docstring formatting engine that processes Python source files
81
- **Configurater**: Command-line and configuration file management
82
- **Encoder**: File encoding detection and line ending handling
83
- **String Functions**: Text manipulation utilities for docstring processing
84
- **Syntax Functions**: Advanced docstring syntax analysis and formatting rules
85
- **Utility Functions**: File discovery and range checking helpers
86
87
The formatting process tokenizes Python source code, identifies docstring locations, applies PEP 257 formatting rules, and reconstructs the source while preserving all non-docstring code.
88
89
## Capabilities
90
91
### Core Formatting
92
93
Main docstring formatting functionality including the Formatter class for processing files and individual docstrings, with support for various formatting options and compatibility modes.
94
95
```python { .api }
96
class Formatter:
97
def __init__(self, args, stderror, stdin, stdout): ...
98
def do_format_files(self) -> int: ...
99
def do_format_standard_in(self, parser): ...
100
101
class FormatResult:
102
ok = 0
103
error = 1
104
interrupted = 2
105
check_failed = 3
106
```
107
108
[Core Formatting](./core-formatting.md)
109
110
### Configuration Management
111
112
Configuration handling for command-line arguments and configuration files, supporting pyproject.toml, setup.cfg, and tox.ini configuration sources.
113
114
```python { .api }
115
class Configurater:
116
def __init__(self, args: List[Union[bool, int, str]]): ...
117
def do_parse_arguments(self) -> None: ...
118
119
parser: argparse.ArgumentParser
120
args: argparse.Namespace
121
flargs_dct: Dict[str, Union[bool, float, int, str]]
122
configuration_file_lst: List[str]
123
```
124
125
[Configuration Management](./configuration.md)
126
127
### String Processing
128
129
Text manipulation utilities for docstring processing including indentation detection, line normalization, summary formatting, and text splitting operations.
130
131
```python { .api }
132
def find_shortest_indentation(lines: List[str]) -> str: ...
133
def normalize_summary(summary: str, noncap: Optional[List[str]] = None) -> str: ...
134
def split_summary_and_description(contents): ...
135
def normalize_line(line: str, newline: str) -> str: ...
136
def split_first_sentence(text): ...
137
```
138
139
[String Processing](./string-processing.md)
140
141
### Syntax Analysis
142
143
Advanced docstring syntax analysis and formatting for field lists, code blocks, URLs, and various docstring styles including Sphinx, Epytext, Google, and NumPy formats.
144
145
```python { .api }
146
def do_find_field_lists(text: str, style: str) -> List[Tuple[int, int]]: ...
147
def wrap_description(text, indentation, wrap_length, force_wrap, strict, rest_sections, style="sphinx"): ...
148
def is_some_sort_of_list(text, strict=True): ...
149
def do_wrap_field_lists(text: str, field_idx: List[Tuple[int, int]], lines: List[str], text_idx: int, indentation: str, wrap_length: int) -> Tuple[List[str], int]: ...
150
```
151
152
[Syntax Analysis](./syntax-analysis.md)
153
154
### File I/O and Encoding
155
156
File encoding detection, line ending handling, and file opening utilities for robust text file processing across different encodings and platforms.
157
158
```python { .api }
159
class Encoder:
160
def __init__(self): ...
161
def do_detect_encoding(self, filename) -> None: ...
162
def do_find_newline(self, source: List[str]) -> str: ...
163
def do_open_with_encoding(self, filename, mode: str = "r"): ...
164
165
CR: str
166
LF: str
167
CRLF: str
168
DEFAULT_ENCODING: str
169
```
170
171
[File I/O and Encoding](./file-io.md)
172
173
## Configuration Options
174
175
Docformatter supports extensive configuration through command-line arguments and configuration files:
176
177
### Format Control
178
- `--black`: Black formatter compatibility mode
179
- `--wrap-summaries LENGTH`: Summary line wrapping length
180
- `--wrap-descriptions LENGTH`: Description wrapping length
181
- `--force-wrap`: Force wrapping even if messy
182
- `--make-summary-multi-line`: Convert single-line to multi-line
183
- `--close-quotes-on-newline`: Close quotes positioning
184
185
### Content Control
186
- `--blank`: Add blank line after description
187
- `--pre-summary-newline`: Add newline before summary
188
- `--pre-summary-space`: Add space after opening quotes
189
- `--non-cap WORDS`: Words not to capitalize in summary
190
191
### Processing Control
192
- `--in-place`: Modify files in place
193
- `--check`: Check formatting without changes
194
- `--diff`: Show differences
195
- `--recursive`: Process directories recursively
196
- `--exclude PATTERNS`: Exclude files/directories
197
198
### Style Control
199
- `--style STYLE`: Docstring style (sphinx, epytext)
200
- `--non-strict`: Relaxed reST syntax checking
201
- `--range START END`: Process specific line ranges
202
- `--docstring-length MIN MAX`: Process specific docstring lengths
203
204
## Version Information
205
206
```python { .api }
207
__version__: str # "1.7.7"
208
```
209
210
## Error Handling
211
212
Docformatter handles various error conditions gracefully:
213
214
- **Encoding Errors**: Automatic encoding detection with fallback to latin-1
215
- **Syntax Errors**: Skips malformed Python files with error reporting
216
- **File Access**: Handles permission and file not found errors
217
- **Keyboard Interrupt**: Clean exit with interrupted status code
218
- **Configuration Errors**: Clear error messages for invalid arguments
219
220
## Integration Features
221
222
- **Pre-commit Hooks**: Native pre-commit hook support via `.pre-commit-hooks.yaml`
223
- **CI/CD Integration**: Check mode returns appropriate exit codes for automation
224
- **Black Compatibility**: `--black` option ensures compatibility with Black formatter
225
- **Configuration Files**: Support for pyproject.toml, setup.cfg, and tox.ini
226
- **Multiple Python Versions**: Compatible with Python 3.9-3.12 and PyPy