0
# Core Formatting API
1
2
The core formatting API provides the primary functions for formatting Python code. These functions handle string formatting, file formatting, and tree-based formatting with configurable styles and selective line formatting.
3
4
## Capabilities
5
6
### String Formatting
7
8
Format Python code provided as a string, with options for custom styles, selective line formatting, and diff output.
9
10
```python { .api }
11
def FormatCode(unformatted_source, filename='<unknown>', style_config=None, lines=None, print_diff=False):
12
"""
13
Format a string of Python code.
14
15
Args:
16
unformatted_source (str): The code to format
17
filename (str): Name of file being reformatted (default: '<unknown>')
18
style_config (str): Either a style name ('pep8', 'google', 'facebook') or path to style file
19
lines (list): List of (start, end) tuples for line ranges to format (1-indexed)
20
print_diff (bool): Return unified diff instead of formatted code
21
22
Returns:
23
tuple: (reformatted_source, changed)
24
- reformatted_source (str): Formatted code or diff if print_diff=True
25
- changed (bool): True if source was modified
26
"""
27
```
28
29
Usage examples:
30
31
```python
32
from yapf.yapflib.yapf_api import FormatCode
33
34
# Basic formatting
35
code = "x=[1,2,3]\nprint(x)"
36
formatted, changed = FormatCode(code)
37
print(formatted)
38
# x = [1, 2, 3]
39
# print(x)
40
41
# Format with Google style
42
formatted, changed = FormatCode(code, style_config='google')
43
44
# Format specific lines only
45
formatted, changed = FormatCode(code, lines=[(1, 1)]) # Format only first line
46
47
# Get diff instead of formatted code
48
diff, changed = FormatCode(code, print_diff=True)
49
print(diff) # Shows unified diff
50
```
51
52
### File Formatting
53
54
Format Python files directly from the filesystem with automatic encoding detection and optional in-place editing.
55
56
```python { .api }
57
def FormatFile(filename, style_config=None, lines=None, print_diff=False, in_place=False, logger=None):
58
"""
59
Format a single Python file.
60
61
Args:
62
filename (str): Path to file to reformat
63
style_config (str): Either a style name or path to style file
64
lines (list): List of (start, end) tuples for line ranges to format (1-indexed)
65
print_diff (bool): Return diff instead of formatted code
66
in_place (bool): Write reformatted code back to the file
67
logger: Function to call for logging (e.g., logging.warning)
68
69
Returns:
70
tuple: (reformatted_code, encoding, changed)
71
- reformatted_code (str): Formatted code (None if in_place=True)
72
- encoding (str): File encoding detected
73
- changed (bool): True if file was modified
74
75
Raises:
76
IOError: If there was an error reading the file
77
ValueError: If both in_place and print_diff are True
78
"""
79
```
80
81
Usage examples:
82
83
```python
84
from yapf.yapflib.yapf_api import FormatFile
85
86
# Format file and return result
87
result, encoding, changed = FormatFile('my_script.py')
88
if changed:
89
print("File was reformatted")
90
print(result)
91
92
# Format file in place
93
_, encoding, changed = FormatFile('my_script.py', in_place=True)
94
95
# Get diff of changes
96
diff, encoding, changed = FormatFile('my_script.py', print_diff=True)
97
98
# Format with custom style and logging
99
import logging
100
result, encoding, changed = FormatFile(
101
'my_script.py',
102
style_config='google',
103
logger=logging.warning
104
)
105
```
106
107
### Tree Formatting
108
109
Format a pre-parsed lib2to3 syntax tree, useful for integration with other tools that work with Python ASTs.
110
111
```python { .api }
112
def FormatTree(tree, style_config=None, lines=None):
113
"""
114
Format a parsed lib2to3 pytree.
115
116
Args:
117
tree: Root node of the pytree to format
118
style_config (str): Either a style name or path to style file
119
lines (list): List of (start, end) tuples for line ranges to format (1-indexed)
120
121
Returns:
122
str: The formatted source code
123
"""
124
```
125
126
Usage example:
127
128
```python
129
from yapf.yapflib.yapf_api import FormatTree
130
from yapf.pytree import pytree_utils
131
132
# Parse code to tree
133
code = "def hello(): print('world')"
134
tree = pytree_utils.ParseCodeToTree(code)
135
136
# Format the tree
137
formatted = FormatTree(tree, style_config='pep8')
138
print(formatted)
139
```
140
141
### AST Formatting
142
143
Format code from a lib2to3 AST representation.
144
145
```python { .api }
146
def FormatAST(ast, style_config=None, lines=None):
147
"""
148
Format a parsed lib2to3 AST.
149
150
Args:
151
ast: AST to format (typically from lib2to3 parsing)
152
style_config (str): Either a style name or path to style file
153
lines (list): List of (start, end) tuples for line ranges to format (1-indexed)
154
155
Returns:
156
str: The formatted source code
157
"""
158
```
159
160
Usage example:
161
162
```python
163
from yapf.yapflib.yapf_api import FormatAST
164
165
# Format an AST (assumes you have an AST from lib2to3 parsing)
166
formatted = FormatAST(ast, style_config='pep8')
167
print(formatted)
168
```
169
170
### File Reading
171
172
Read Python files with proper encoding detection and line ending preservation.
173
174
```python { .api }
175
def ReadFile(filename, logger=None):
176
"""
177
Read file contents with encoding detection.
178
179
Args:
180
filename (str): Path to file to read
181
logger: Function to call for logging errors
182
183
Returns:
184
tuple: (source, line_ending, encoding)
185
- source (str): File contents with normalized line endings
186
- line_ending (str): Original line ending style ('\\n', '\\r\\n', etc.)
187
- encoding (str): Detected file encoding
188
189
Raises:
190
IOError: If file cannot be read
191
UnicodeDecodeError: If file cannot be decoded
192
"""
193
```
194
195
Usage example:
196
197
```python
198
from yapf.yapflib.yapf_api import ReadFile
199
200
# Read file with encoding detection
201
source, line_ending, encoding = ReadFile('my_script.py')
202
print(f"File encoding: {encoding}")
203
print(f"Line ending: {repr(line_ending)}")
204
```
205
206
## Error Handling
207
208
All formatting functions may raise `YapfError` exceptions for various error conditions:
209
210
```python
211
from yapf.yapflib.errors import YapfError
212
from yapf.yapflib.yapf_api import FormatCode
213
214
try:
215
formatted, changed = FormatCode("invalid python syntax +++")
216
except YapfError as e:
217
print(f"Formatting error: {e}")
218
```
219
220
## Integration Patterns
221
222
### IDE Integration
223
224
```python
225
from yapf.yapflib.yapf_api import FormatCode
226
227
def format_selection(code, start_line, end_line):
228
"""Format specific lines in an editor."""
229
lines = [(start_line, end_line)]
230
formatted, changed = FormatCode(code, lines=lines)
231
return formatted if changed else code
232
233
def format_on_save(filename):
234
"""Format file on save."""
235
from yapf.yapflib.yapf_api import FormatFile
236
_, _, changed = FormatFile(filename, in_place=True)
237
return changed
238
```
239
240
### Batch Processing
241
242
```python
243
import os
244
from yapf.yapflib.yapf_api import FormatFile
245
246
def format_project(directory, style='pep8'):
247
"""Format all Python files in a project."""
248
for root, dirs, files in os.walk(directory):
249
for file in files:
250
if file.endswith('.py'):
251
filepath = os.path.join(root, file)
252
try:
253
_, _, changed = FormatFile(
254
filepath,
255
style_config=style,
256
in_place=True
257
)
258
if changed:
259
print(f"Formatted: {filepath}")
260
except Exception as e:
261
print(f"Error formatting {filepath}: {e}")
262
```