0
# Configuration and Modes
1
2
Black's configuration system controls all formatting behavior through the Mode class and associated enums for target versions, language features, and preview options.
3
4
## Capabilities
5
6
### Mode Configuration
7
8
The central configuration class that controls all aspects of Black's formatting behavior.
9
10
```python { .api }
11
@dataclass
12
class Mode:
13
"""
14
Configuration for Black formatting behavior.
15
"""
16
target_versions: set[TargetVersion] = field(default_factory=set)
17
line_length: int = 88
18
string_normalization: bool = True
19
is_pyi: bool = False
20
is_ipynb: bool = False
21
skip_source_first_line: bool = False
22
magic_trailing_comma: bool = True
23
python_cell_magics: set[str] = field(default_factory=set)
24
preview: bool = False
25
unstable: bool = False
26
enabled_features: set[Preview] = field(default_factory=set)
27
28
def __contains__(self, feature: Preview) -> bool:
29
"""Check if a preview feature is enabled."""
30
31
def get_cache_key(self) -> str:
32
"""Generate cache key for this configuration."""
33
```
34
35
#### Mode Parameters
36
37
- **target_versions**: Set of Python versions to support (default: auto-detect)
38
- **line_length**: Maximum line length in characters (default: 88)
39
- **string_normalization**: Normalize string quotes to double quotes (default: True)
40
- **is_pyi**: Format as .pyi stub file with relaxed rules (default: False)
41
- **is_ipynb**: Format as Jupyter notebook with special handling (default: False)
42
- **skip_source_first_line**: Skip shebang lines when formatting (default: False)
43
- **magic_trailing_comma**: Use trailing commas to force line splits (default: True)
44
- **python_cell_magics**: Set of IPython cell magics to recognize (default: empty)
45
- **preview**: Enable all preview features (default: False)
46
- **unstable**: Enable unstable features (default: False)
47
- **enabled_features**: Specific preview features to enable (default: empty)
48
49
### Target Version System
50
51
Enumeration of supported Python versions with automatic feature compatibility checking.
52
53
```python { .api }
54
class TargetVersion(Enum):
55
"""Python version enumeration for compatibility targeting."""
56
PY33 = 3, 3
57
PY34 = 3, 4
58
PY35 = 3, 5
59
PY36 = 3, 6
60
PY37 = 3, 7
61
PY38 = 3, 8
62
PY39 = 3, 9
63
PY310 = 3, 10
64
PY311 = 3, 11
65
PY312 = 3, 12
66
PY313 = 3, 13
67
68
def pretty(self) -> str:
69
"""Return human-readable version string (e.g., 'Python 3.9')."""
70
```
71
72
### Language Features
73
74
Enumeration of Python language features used for version compatibility analysis.
75
76
```python { .api }
77
class Feature(Enum):
78
"""Python language features for compatibility checking."""
79
F_STRINGS = 1
80
NUMERIC_UNDERSCORES = 2
81
TRAILING_COMMA_IN_CALL = 3
82
TRAILING_COMMA_IN_DEF = 4
83
ASYNC_IDENTIFIERS = 5
84
ASYNC_KEYWORDS = 6
85
ASSIGNMENT_EXPRESSIONS = 7
86
POS_ONLY_ARGUMENTS = 8
87
RELAXED_DECORATORS = 9
88
PATTERN_MATCHING = 10
89
UNPACKING_ON_FLOW = 11
90
ANN_ASSIGN_EXTENDED_RHS = 12
91
EXCEPT_STAR = 13
92
VARIADIC_GENERICS = 14
93
DEBUG_F_STRINGS = 15
94
PARENTHESIZED_CONTEXT_MANAGERS = 16
95
TYPE_PARAMS = 17
96
FSTRING_PARSING = 18
97
TYPE_PARAM_DEFAULTS = 19
98
FORCE_OPTIONAL_PARENTHESES = 20
99
FUTURE_ANNOTATIONS = 21
100
```
101
102
### Preview Features
103
104
Individual preview features that can be enabled independently for experimental formatting behaviors.
105
106
```python { .api }
107
class Preview(Enum):
108
"""Individual preview features for experimental formatting."""
109
string_processing = 1
110
hug_parens_with_braces_and_square_brackets = 2
111
wrap_long_dict_values_in_parens = 3
112
multiline_string_handling = 4
113
always_one_newline_after_import = 5
114
```
115
116
### Write-Back Modes
117
118
Configuration for output behavior when formatting files.
119
120
```python { .api }
121
class WriteBack(Enum):
122
"""Output modes for file formatting."""
123
NO = 0 # No output, just return status
124
YES = 1 # Write formatted content to file
125
DIFF = 2 # Output unified diff
126
CHECK = 3 # Check only, exit with error if changes needed
127
COLOR_DIFF = 4 # Output colored diff
128
129
@classmethod
130
def from_configuration(cls, *, check: bool, diff: bool, color: bool = False) -> WriteBack:
131
"""Create WriteBack mode from boolean flags."""
132
```
133
134
### Feature Support Functions
135
136
Utility functions for checking feature compatibility across Python versions.
137
138
```python { .api }
139
def supports_feature(target_versions: set[TargetVersion], feature: Feature) -> bool:
140
"""
141
Check if a feature is supported by all target versions.
142
143
Parameters:
144
- target_versions: Set of Python versions to check
145
- feature: Language feature to validate
146
147
Returns:
148
True if feature is supported by all target versions
149
"""
150
```
151
152
### Configuration Loading
153
154
Functions for loading Black configuration from pyproject.toml files.
155
156
```python { .api }
157
def read_pyproject_toml(ctx: click.Context, param: click.Parameter, value: Optional[str]) -> Optional[str]:
158
"""
159
Parse Black configuration from pyproject.toml.
160
161
Parameters:
162
- ctx: Click context
163
- param: Click parameter
164
- value: Optional path to configuration file
165
166
Returns:
167
Path to configuration file if found
168
"""
169
170
def validate_regex(ctx: click.Context, param: click.Parameter, value: Optional[str]) -> Optional[Pattern[str]]:
171
"""
172
Validate regex patterns for CLI options.
173
174
Parameters:
175
- ctx: Click context
176
- param: Click parameter
177
- value: Regex pattern string
178
179
Returns:
180
Compiled regex pattern or None
181
182
Raises:
183
- click.BadParameter: If regex is invalid
184
"""
185
```
186
187
## Constants
188
189
### Version Feature Mapping
190
191
```python { .api }
192
# Maps Python versions to supported language features
193
VERSION_TO_FEATURES: dict[TargetVersion, set[Feature]]
194
195
# Maps __future__ imports to Feature enums
196
FUTURE_FLAG_TO_FEATURE: dict[str, Feature]
197
198
# Set of unstable preview features
199
UNSTABLE_FEATURES: set[Preview]
200
```
201
202
## Usage Examples
203
204
### Basic Mode Configuration
205
206
```python
207
import black
208
209
# Default configuration
210
mode = black.Mode()
211
212
# Custom line length
213
mode = black.Mode(line_length=79)
214
215
# Target specific Python versions
216
mode = black.Mode(
217
target_versions={black.TargetVersion.PY39, black.TargetVersion.PY310}
218
)
219
220
# Disable string normalization
221
mode = black.Mode(string_normalization=False)
222
223
# Format as stub file (.pyi)
224
mode = black.Mode(is_pyi=True)
225
```
226
227
### Preview Features
228
229
```python
230
# Enable all preview features
231
mode = black.Mode(preview=True)
232
233
# Enable specific preview features
234
mode = black.Mode(
235
preview=True,
236
enabled_features={
237
black.Preview.string_processing,
238
black.Preview.wrap_long_dict_values_in_parens
239
}
240
)
241
242
# Check if feature is enabled
243
if black.Preview.string_processing in mode:
244
print("String processing enabled")
245
246
# Enable unstable features
247
mode = black.Mode(unstable=True)
248
```
249
250
### Jupyter Notebook Configuration
251
252
```python
253
# Configure for Jupyter notebooks
254
mode = black.Mode(
255
is_ipynb=True,
256
python_cell_magics={'%%time', '%%timeit', '%%capture'}
257
)
258
259
# Format with custom cell magics
260
code = """
261
%%time
262
def slow_function():
263
time.sleep(1)
264
return "done"
265
"""
266
267
formatted = black.format_cell(code, fast=False, mode=mode)
268
```
269
270
### Version Compatibility
271
272
```python
273
# Check feature support
274
versions = {black.TargetVersion.PY38, black.TargetVersion.PY39}
275
supports_walrus = black.supports_feature(versions, black.Feature.ASSIGNMENT_EXPRESSIONS)
276
print(f"Assignment expressions supported: {supports_walrus}")
277
278
# Auto-detect compatible versions
279
import ast
280
code = "x := 1" # Assignment expression (Python 3.8+)
281
tree = ast.parse(code)
282
node = black.lib2to3_parse(code)
283
compatible = black.detect_target_versions(node)
284
print(f"Compatible versions: {compatible}")
285
```
286
287
### File Processing Modes
288
289
```python
290
from pathlib import Path
291
292
# Different write-back modes
293
modes = [
294
black.WriteBack.NO, # Just check, don't modify
295
black.WriteBack.YES, # Write changes to file
296
black.WriteBack.DIFF, # Show diff
297
black.WriteBack.CHECK, # Exit with error if changes needed
298
black.WriteBack.COLOR_DIFF # Show colored diff
299
]
300
301
for write_mode in modes:
302
changed = black.format_file_in_place(
303
Path("example.py"),
304
fast=False,
305
mode=black.Mode(),
306
write_back=write_mode
307
)
308
```
309
310
## Types
311
312
```python { .api }
313
# Legacy alias for backwards compatibility
314
FileMode = Mode
315
316
# Set types for configuration
317
TargetVersionSet = set[TargetVersion]
318
FeatureSet = set[Feature]
319
PreviewSet = set[Preview]
320
```