0
# Core Formatting Functions
1
2
Primary API functions for formatting Python code, providing both string-based and file-based formatting capabilities with comprehensive safety checks and validation.
3
4
## Capabilities
5
6
### String Formatting
7
8
The primary entry point for programmatic code formatting, taking source code as a string and returning formatted code.
9
10
```python { .api }
11
def format_str(src_contents: str, *, mode: Mode, lines: Collection[tuple[int, int]] = ()) -> str:
12
"""
13
Format Python source code string.
14
15
Parameters:
16
- src_contents: Python source code to format
17
- mode: Mode configuration controlling formatting behavior
18
- lines: Optional line ranges to format (tuple of start, end line numbers)
19
20
Returns:
21
Formatted Python source code string
22
23
Raises:
24
- InvalidInput: If source code cannot be parsed
25
- NothingChanged: If no formatting changes are needed
26
"""
27
```
28
29
### File Content Formatting
30
31
Formats file contents with optional AST safety checks, used internally by command line and server implementations.
32
33
```python { .api }
34
def format_file_contents(src_contents: str, *, fast: bool, mode: Mode, lines: Collection[tuple[int, int]] = ()) -> str:
35
"""
36
Format file contents with safety checks.
37
38
Parameters:
39
- src_contents: File contents to format
40
- fast: Skip AST safety checks if True
41
- mode: Mode configuration controlling formatting behavior
42
- lines: Optional line ranges to format
43
44
Returns:
45
Formatted file contents
46
47
Raises:
48
- InvalidInput: If source cannot be parsed
49
- NothingChanged: If no formatting changes needed
50
- ASTSafetyError: If formatted code is not AST-equivalent (when fast=False)
51
"""
52
```
53
54
### In-Place File Formatting
55
56
Formats files directly on disk with configurable write-back behavior and automatic file type detection.
57
58
```python { .api }
59
def format_file_in_place(
60
src: Path,
61
fast: bool,
62
mode: Mode,
63
write_back: WriteBack = WriteBack.NO,
64
lock: Any = None,
65
*,
66
lines: Collection[tuple[int, int]] = ()
67
) -> bool:
68
"""
69
Format a file in place on disk.
70
71
Parameters:
72
- src: Path to source file to format
73
- fast: Skip AST safety checks if True
74
- mode: Mode configuration controlling formatting behavior
75
- write_back: Output behavior (NO, YES, DIFF, CHECK, COLOR_DIFF)
76
- lock: Optional threading lock for concurrent access
77
- lines: Optional line ranges to format
78
79
Returns:
80
True if file was changed, False otherwise
81
82
Note:
83
Automatically detects .pyi and .ipynb file modes based on extension
84
"""
85
```
86
87
### Single File Formatting
88
89
Format a single file with full error handling and reporting integration.
90
91
```python { .api }
92
def reformat_one(
93
src: Path,
94
fast: bool,
95
write_back: WriteBack,
96
mode: Mode,
97
report: Report,
98
*,
99
lines: Collection[tuple[int, int]] = ()
100
) -> None:
101
"""
102
Reformat a single file under `src` without spawning child processes.
103
104
Parameters:
105
- src: Path to source file to format (supports stdin via "-")
106
- fast: Skip AST safety checks if True
107
- write_back: Output behavior (NO, YES, DIFF, CHECK, COLOR_DIFF)
108
- mode: Mode configuration controlling formatting behavior
109
- report: Report object to track results and failures
110
- lines: Optional line ranges to format
111
112
Note:
113
- Handles stdin input when src is "-" or starts with STDIN_PLACEHOLDER
114
- Automatically detects .pyi and .ipynb modes from file extension
115
- Integrates with cache system for performance optimization
116
- Updates the provided Report object with results
117
"""
118
```
119
120
### AST Safety Validation
121
122
Functions to ensure formatted code maintains semantic equivalence and formatting stability.
123
124
```python { .api }
125
def assert_equivalent(src: str, dst: str) -> None:
126
"""
127
Validate that formatted code is AST-equivalent to source.
128
129
Parameters:
130
- src: Original source code
131
- dst: Formatted code
132
133
Raises:
134
- AssertionError: If ASTs are not equivalent
135
"""
136
137
def assert_stable(src: str, dst: str, mode: Mode, *, lines: Collection[tuple[int, int]] = ()) -> None:
138
"""
139
Ensure formatting is stable (second pass produces same result).
140
141
Parameters:
142
- src: Original source code
143
- dst: First formatting pass result
144
- mode: Mode configuration used for formatting
145
- lines: Line ranges that were formatted
146
147
Raises:
148
- AssertionError: If second formatting pass differs
149
"""
150
```
151
152
### Feature Analysis
153
154
Functions for analyzing Python code to determine language features and compatible Python versions.
155
156
```python { .api }
157
def get_features_used(node: Node, *, future_imports: Optional[set[str]] = None) -> set[Feature]:
158
"""
159
Analyze AST to determine Python language features used.
160
161
Parameters:
162
- node: AST node to analyze
163
- future_imports: Set of __future__ import names
164
165
Returns:
166
Set of Feature enum values found in the code
167
"""
168
169
def detect_target_versions(node: Node, *, future_imports: Optional[set[str]] = None) -> set[TargetVersion]:
170
"""
171
Determine compatible Python versions based on code features.
172
173
Parameters:
174
- node: AST node to analyze
175
- future_imports: Set of __future__ import names
176
177
Returns:
178
Set of TargetVersion enums that support all detected features
179
"""
180
181
def get_future_imports(node: Node) -> set[str]:
182
"""
183
Extract __future__ import statements from AST.
184
185
Parameters:
186
- node: AST node to analyze
187
188
Returns:
189
Set of __future__ import names found
190
"""
191
```
192
193
### Encoding Utilities
194
195
Utility functions for handling file encoding and line ending detection.
196
197
```python { .api }
198
def decode_bytes(src: bytes) -> tuple[str, str, str]:
199
"""
200
Decode byte content to string with encoding and newline detection.
201
202
Parameters:
203
- src: Byte content to decode
204
205
Returns:
206
Tuple of (decoded_content, encoding, newline_type)
207
"""
208
```
209
210
## Usage Examples
211
212
### Basic String Formatting
213
214
```python
215
import black
216
217
# Simple formatting
218
code = "def f(arg:str='')->None:pass"
219
formatted = black.format_str(code, mode=black.Mode())
220
print(formatted)
221
# Output: def f(arg: str = "") -> None:
222
# pass
223
224
# Custom line length
225
mode = black.Mode(line_length=79)
226
formatted = black.format_str(code, mode=mode)
227
228
# Format specific lines only
229
lines = [(1, 5), (10, 15)] # Line ranges to format
230
formatted = black.format_str(code, mode=black.Mode(), lines=lines)
231
```
232
233
### File Formatting with Safety Checks
234
235
```python
236
from pathlib import Path
237
238
# Format file with full safety checks
239
try:
240
changed = black.format_file_in_place(
241
Path("script.py"),
242
fast=False, # Enable AST safety checks
243
mode=black.Mode(),
244
write_back=black.WriteBack.YES
245
)
246
if changed:
247
print("File was reformatted")
248
else:
249
print("File was already formatted")
250
except black.NothingChanged:
251
print("No changes needed")
252
except black.InvalidInput as e:
253
print(f"Cannot format file: {e}")
254
```
255
256
### Single File Formatting with Reporting
257
258
```python
259
from pathlib import Path
260
import black
261
262
# Setup for single file formatting with reporting
263
report = black.Report(verbose=True)
264
mode = black.Mode(line_length=88)
265
266
# Format single file with full reporting
267
black.reformat_one(
268
Path("example.py"),
269
fast=False,
270
write_back=black.WriteBack.YES,
271
mode=mode,
272
report=report
273
)
274
275
# Check results
276
print(f"Files changed: {report.change_count}")
277
print(f"Files failed: {report.failure_count}")
278
print(f"Exit code: {report.return_code}")
279
```
280
281
### Feature Detection
282
283
```python
284
import ast
285
import black
286
287
code = """
288
def func(x: int, /) -> int: # Positional-only parameter
289
return x | 2 # Union operator
290
"""
291
292
# Parse and analyze features
293
tree = ast.parse(code)
294
node = black.lib2to3_parse(code)
295
features = black.get_features_used(node)
296
compatible_versions = black.detect_target_versions(node)
297
298
print(f"Features used: {features}")
299
print(f"Compatible Python versions: {compatible_versions}")
300
```
301
302
## Types
303
304
```python { .api }
305
# Type aliases used by formatting functions
306
FileContent = str
307
Encoding = str
308
NewLine = str
309
310
# From blib2to3 (AST processing)
311
Node = blib2to3.pytree.Node
312
Leaf = blib2to3.pytree.Leaf
313
314
# Collection type for line ranges
315
Collection = typing.Collection
316
```