0
# Style Configuration
1
2
YAPF's style configuration system provides comprehensive control over code formatting through predefined styles, custom configuration files, and programmatic settings. The style system supports hierarchical configuration with local overrides and extensive customization options.
3
4
## Capabilities
5
6
### Style Management
7
8
Core functions for getting, setting, and managing formatting styles.
9
10
```python { .api }
11
def Get(setting_name):
12
"""
13
Get the value of a style setting.
14
15
Args:
16
setting_name (str): Name of the style setting
17
18
Returns:
19
The current value of the setting
20
"""
21
22
def GetOrDefault(setting_name, default_value):
23
"""
24
Get a style setting or return default if not set.
25
26
Args:
27
setting_name (str): Name of the style setting
28
default_value: Value to return if setting doesn't exist
29
30
Returns:
31
Setting value or default_value
32
"""
33
34
def SetGlobalStyle(style):
35
"""
36
Set the global style configuration.
37
38
Args:
39
style (dict): Style configuration dictionary
40
"""
41
42
def Help():
43
"""
44
Get help information for all style settings.
45
46
Returns:
47
dict: Mapping of style setting names to help strings
48
"""
49
```
50
51
### Style Creation
52
53
Create style configurations from various sources.
54
55
```python { .api }
56
def CreateStyleFromConfig(style_config):
57
"""
58
Create a style configuration from config string or file.
59
60
Args:
61
style_config (str): Style name ('pep8', 'google', 'facebook', 'yapf')
62
or path to configuration file
63
64
Returns:
65
dict: Style configuration dictionary
66
67
Raises:
68
StyleConfigError: If configuration cannot be loaded
69
"""
70
```
71
72
## Usage Examples
73
74
### Using Predefined Styles
75
76
```python
77
from yapf.yapflib import style
78
from yapf.yapflib.yapf_api import FormatCode
79
80
# Set PEP 8 style globally
81
pep8_style = style.CreateStyleFromConfig('pep8')
82
style.SetGlobalStyle(pep8_style)
83
84
# Format with Google style
85
code = "x=[1,2,3]"
86
formatted, _ = FormatCode(code, style_config='google')
87
88
# Format with Facebook style
89
formatted, _ = FormatCode(code, style_config='facebook')
90
91
# Format with YAPF default style
92
formatted, _ = FormatCode(code, style_config='yapf')
93
```
94
95
### Working with Style Settings
96
97
```python
98
from yapf.yapflib import style
99
100
# Create and set a custom style
101
custom_style = style.CreateStyleFromConfig('pep8')
102
style.SetGlobalStyle(custom_style)
103
104
# Get current setting values
105
indent_width = style.Get('INDENT_WIDTH')
106
column_limit = style.Get('COLUMN_LIMIT')
107
print(f"Indent: {indent_width}, Column limit: {column_limit}")
108
109
# Get setting with default
110
use_tabs = style.GetOrDefault('USE_TABS', False)
111
112
# Get help for all settings
113
help_info = style.Help()
114
for setting, description in help_info.items():
115
print(f"{setting}: {description}")
116
```
117
118
### Custom Configuration Files
119
120
YAPF supports multiple configuration file formats:
121
122
#### .style.yapf file
123
124
```ini
125
[style]
126
based_on_style = pep8
127
column_limit = 100
128
indent_width = 4
129
split_before_logical_operator = true
130
```
131
132
#### pyproject.toml configuration
133
134
```toml
135
[tool.yapf]
136
based_on_style = "pep8"
137
column_limit = 100
138
indent_width = 4
139
split_before_logical_operator = true
140
```
141
142
#### setup.cfg configuration
143
144
```ini
145
[yapf]
146
based_on_style = pep8
147
column_limit = 100
148
indent_width = 4
149
split_before_logical_operator = true
150
```
151
152
### Loading Custom Configurations
153
154
```python
155
from yapf.yapflib import style
156
157
# Load from file
158
custom_style = style.CreateStyleFromConfig('/path/to/.style.yapf')
159
style.SetGlobalStyle(custom_style)
160
161
# Load from pyproject.toml
162
custom_style = style.CreateStyleFromConfig('/path/to/pyproject.toml')
163
style.SetGlobalStyle(custom_style)
164
```
165
166
## Key Style Settings
167
168
### Indentation and Spacing
169
170
```python
171
# Common indentation settings
172
style_config = {
173
'INDENT_WIDTH': 4, # Number of spaces per indent level
174
'USE_TABS': False, # Use tabs instead of spaces
175
'CONTINUATION_INDENT_WIDTH': 4, # Indent for line continuations
176
'INDENT_CLOSING_BRACKETS': False, # Indent closing brackets
177
}
178
```
179
180
### Line Length and Breaking
181
182
```python
183
# Line length settings
184
style_config = {
185
'COLUMN_LIMIT': 79, # Maximum line length
186
'SPLIT_BEFORE_LOGICAL_OPERATOR': True, # Split before logical operators
187
'SPLIT_BEFORE_ARITHMETIC_OPERATOR': False, # Split before arithmetic operators
188
'ALLOW_SPLIT_BEFORE_DICT_VALUE': True, # Allow split before dict values
189
}
190
```
191
192
### Alignment and Formatting
193
194
```python
195
# Alignment settings
196
style_config = {
197
'ALIGN_CLOSING_BRACKET_WITH_VISUAL_INDENT': True,
198
'ALLOW_MULTILINE_LAMBDAS': False,
199
'ALLOW_MULTILINE_DICTIONARY_KEYS': False,
200
'ARITHMETIC_PRECEDENCE_INDICATION': False,
201
}
202
```
203
204
## Predefined Styles
205
206
### PEP 8 Style
207
Based on the official Python style guide (PEP 8).
208
209
```python
210
formatted, _ = FormatCode(code, style_config='pep8')
211
```
212
213
### Google Style
214
Based on Google's Python style guide.
215
216
```python
217
formatted, _ = FormatCode(code, style_config='google')
218
```
219
220
Key differences from PEP 8:
221
- 4-space hanging indents
222
- Spaces around default parameter values
223
- Different line continuation rules
224
225
### Facebook Style
226
Based on Facebook's internal Python style guide.
227
228
```python
229
formatted, _ = FormatCode(code, style_config='facebook')
230
```
231
232
### YAPF Style
233
YAPF's own default style.
234
235
```python
236
formatted, _ = FormatCode(code, style_config='yapf')
237
```
238
239
## Style Configuration Hierarchy
240
241
YAPF searches for configuration in this order:
242
243
1. Command line `--style` parameter
244
2. `.style.yapf` in current directory or parent directories
245
3. `pyproject.toml` with `[tool.yapf]` section
246
4. `setup.cfg` with `[yapf]` section
247
5. Default style (PEP 8)
248
249
### Programmatic Style Discovery
250
251
```python
252
from yapf.yapflib import file_resources
253
254
# Get default style for a directory
255
style_config = file_resources.GetDefaultStyleForDir('/path/to/project')
256
257
# This searches up the directory tree for configuration files
258
```
259
260
## Error Handling
261
262
```python { .api }
263
class StyleConfigError(YapfError):
264
"""Raised when there's a problem reading the style configuration."""
265
```
266
267
Example error handling:
268
269
```python
270
from yapf.yapflib import style
271
from yapf.yapflib.errors import StyleConfigError
272
273
try:
274
custom_style = style.CreateStyleFromConfig('/path/to/invalid/config')
275
except StyleConfigError as e:
276
print(f"Style configuration error: {e}")
277
```
278
279
## Advanced Configuration
280
281
### Conditional Formatting
282
283
Disable YAPF formatting for specific sections:
284
285
```python
286
# yapf: disable
287
poorly_formatted = {
288
'key': 'value',
289
'other': 'data'
290
}
291
# yapf: enable
292
```
293
294
Or using fmt comments:
295
296
```python
297
# fmt: off
298
poorly_formatted = {
299
'key': 'value',
300
'other': 'data'
301
}
302
# fmt: on
303
```
304
305
### Integration with Pre-commit
306
307
```yaml
308
# .pre-commit-config.yaml
309
repos:
310
- repo: https://github.com/google/yapf
311
rev: v0.43.0
312
hooks:
313
- id: yapf
314
args: [--style=google]
315
```
316
317
### Custom Style Templates
318
319
Create reusable style configurations:
320
321
```python
322
# my_team_style.py
323
from yapf.yapflib import style
324
325
TEAM_STYLE = {
326
'based_on_style': 'pep8',
327
'column_limit': 100,
328
'indent_width': 4,
329
'split_before_logical_operator': True,
330
'spaces_around_power_operator': True,
331
}
332
333
def apply_team_style():
334
"""Apply team-specific formatting style."""
335
style.SetGlobalStyle(TEAM_STYLE)
336
```