]>
Commit | Line | Data |
---|---|---|
1 | Metadata-Version: 2.1 | |
2 | Name: yapf | |
3 | Version: 0.40.2 | |
4 | Summary: A formatter for Python code | |
5 | Author: Google Inc. | |
6 | Maintainer-email: Bill Wendling <morbo@google.com> | |
7 | License: | |
8 | Apache License | |
9 | Version 2.0, January 2004 | |
10 | http://www.apache.org/licenses/ | |
11 | ||
12 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION | |
13 | ||
14 | 1. Definitions. | |
15 | ||
16 | "License" shall mean the terms and conditions for use, reproduction, | |
17 | and distribution as defined by Sections 1 through 9 of this document. | |
18 | ||
19 | "Licensor" shall mean the copyright owner or entity authorized by | |
20 | the copyright owner that is granting the License. | |
21 | ||
22 | "Legal Entity" shall mean the union of the acting entity and all | |
23 | other entities that control, are controlled by, or are under common | |
24 | control with that entity. For the purposes of this definition, | |
25 | "control" means (i) the power, direct or indirect, to cause the | |
26 | direction or management of such entity, whether by contract or | |
27 | otherwise, or (ii) ownership of fifty percent (50%) or more of the | |
28 | outstanding shares, or (iii) beneficial ownership of such entity. | |
29 | ||
30 | "You" (or "Your") shall mean an individual or Legal Entity | |
31 | exercising permissions granted by this License. | |
32 | ||
33 | "Source" form shall mean the preferred form for making modifications, | |
34 | including but not limited to software source code, documentation | |
35 | source, and configuration files. | |
36 | ||
37 | "Object" form shall mean any form resulting from mechanical | |
38 | transformation or translation of a Source form, including but | |
39 | not limited to compiled object code, generated documentation, | |
40 | and conversions to other media types. | |
41 | ||
42 | "Work" shall mean the work of authorship, whether in Source or | |
43 | Object form, made available under the License, as indicated by a | |
44 | copyright notice that is included in or attached to the work | |
45 | (an example is provided in the Appendix below). | |
46 | ||
47 | "Derivative Works" shall mean any work, whether in Source or Object | |
48 | form, that is based on (or derived from) the Work and for which the | |
49 | editorial revisions, annotations, elaborations, or other modifications | |
50 | represent, as a whole, an original work of authorship. For the purposes | |
51 | of this License, Derivative Works shall not include works that remain | |
52 | separable from, or merely link (or bind by name) to the interfaces of, | |
53 | the Work and Derivative Works thereof. | |
54 | ||
55 | "Contribution" shall mean any work of authorship, including | |
56 | the original version of the Work and any modifications or additions | |
57 | to that Work or Derivative Works thereof, that is intentionally | |
58 | submitted to Licensor for inclusion in the Work by the copyright owner | |
59 | or by an individual or Legal Entity authorized to submit on behalf of | |
60 | the copyright owner. For the purposes of this definition, "submitted" | |
61 | means any form of electronic, verbal, or written communication sent | |
62 | to the Licensor or its representatives, including but not limited to | |
63 | communication on electronic mailing lists, source code control systems, | |
64 | and issue tracking systems that are managed by, or on behalf of, the | |
65 | Licensor for the purpose of discussing and improving the Work, but | |
66 | excluding communication that is conspicuously marked or otherwise | |
67 | designated in writing by the copyright owner as "Not a Contribution." | |
68 | ||
69 | "Contributor" shall mean Licensor and any individual or Legal Entity | |
70 | on behalf of whom a Contribution has been received by Licensor and | |
71 | subsequently incorporated within the Work. | |
72 | ||
73 | 2. Grant of Copyright License. Subject to the terms and conditions of | |
74 | this License, each Contributor hereby grants to You a perpetual, | |
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable | |
76 | copyright license to reproduce, prepare Derivative Works of, | |
77 | publicly display, publicly perform, sublicense, and distribute the | |
78 | Work and such Derivative Works in Source or Object form. | |
79 | ||
80 | 3. Grant of Patent License. Subject to the terms and conditions of | |
81 | this License, each Contributor hereby grants to You a perpetual, | |
82 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable | |
83 | (except as stated in this section) patent license to make, have made, | |
84 | use, offer to sell, sell, import, and otherwise transfer the Work, | |
85 | where such license applies only to those patent claims licensable | |
86 | by such Contributor that are necessarily infringed by their | |
87 | Contribution(s) alone or by combination of their Contribution(s) | |
88 | with the Work to which such Contribution(s) was submitted. If You | |
89 | institute patent litigation against any entity (including a | |
90 | cross-claim or counterclaim in a lawsuit) alleging that the Work | |
91 | or a Contribution incorporated within the Work constitutes direct | |
92 | or contributory patent infringement, then any patent licenses | |
93 | granted to You under this License for that Work shall terminate | |
94 | as of the date such litigation is filed. | |
95 | ||
96 | 4. Redistribution. You may reproduce and distribute copies of the | |
97 | Work or Derivative Works thereof in any medium, with or without | |
98 | modifications, and in Source or Object form, provided that You | |
99 | meet the following conditions: | |
100 | ||
101 | (a) You must give any other recipients of the Work or | |
102 | Derivative Works a copy of this License; and | |
103 | ||
104 | (b) You must cause any modified files to carry prominent notices | |
105 | stating that You changed the files; and | |
106 | ||
107 | (c) You must retain, in the Source form of any Derivative Works | |
108 | that You distribute, all copyright, patent, trademark, and | |
109 | attribution notices from the Source form of the Work, | |
110 | excluding those notices that do not pertain to any part of | |
111 | the Derivative Works; and | |
112 | ||
113 | (d) If the Work includes a "NOTICE" text file as part of its | |
114 | distribution, then any Derivative Works that You distribute must | |
115 | include a readable copy of the attribution notices contained | |
116 | within such NOTICE file, excluding those notices that do not | |
117 | pertain to any part of the Derivative Works, in at least one | |
118 | of the following places: within a NOTICE text file distributed | |
119 | as part of the Derivative Works; within the Source form or | |
120 | documentation, if provided along with the Derivative Works; or, | |
121 | within a display generated by the Derivative Works, if and | |
122 | wherever such third-party notices normally appear. The contents | |
123 | of the NOTICE file are for informational purposes only and | |
124 | do not modify the License. You may add Your own attribution | |
125 | notices within Derivative Works that You distribute, alongside | |
126 | or as an addendum to the NOTICE text from the Work, provided | |
127 | that such additional attribution notices cannot be construed | |
128 | as modifying the License. | |
129 | ||
130 | You may add Your own copyright statement to Your modifications and | |
131 | may provide additional or different license terms and conditions | |
132 | for use, reproduction, or distribution of Your modifications, or | |
133 | for any such Derivative Works as a whole, provided Your use, | |
134 | reproduction, and distribution of the Work otherwise complies with | |
135 | the conditions stated in this License. | |
136 | ||
137 | 5. Submission of Contributions. Unless You explicitly state otherwise, | |
138 | any Contribution intentionally submitted for inclusion in the Work | |
139 | by You to the Licensor shall be under the terms and conditions of | |
140 | this License, without any additional terms or conditions. | |
141 | Notwithstanding the above, nothing herein shall supersede or modify | |
142 | the terms of any separate license agreement you may have executed | |
143 | with Licensor regarding such Contributions. | |
144 | ||
145 | 6. Trademarks. This License does not grant permission to use the trade | |
146 | names, trademarks, service marks, or product names of the Licensor, | |
147 | except as required for reasonable and customary use in describing the | |
148 | origin of the Work and reproducing the content of the NOTICE file. | |
149 | ||
150 | 7. Disclaimer of Warranty. Unless required by applicable law or | |
151 | agreed to in writing, Licensor provides the Work (and each | |
152 | Contributor provides its Contributions) on an "AS IS" BASIS, | |
153 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or | |
154 | implied, including, without limitation, any warranties or conditions | |
155 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A | |
156 | PARTICULAR PURPOSE. You are solely responsible for determining the | |
157 | appropriateness of using or redistributing the Work and assume any | |
158 | risks associated with Your exercise of permissions under this License. | |
159 | ||
160 | 8. Limitation of Liability. In no event and under no legal theory, | |
161 | whether in tort (including negligence), contract, or otherwise, | |
162 | unless required by applicable law (such as deliberate and grossly | |
163 | negligent acts) or agreed to in writing, shall any Contributor be | |
164 | liable to You for damages, including any direct, indirect, special, | |
165 | incidental, or consequential damages of any character arising as a | |
166 | result of this License or out of the use or inability to use the | |
167 | Work (including but not limited to damages for loss of goodwill, | |
168 | work stoppage, computer failure or malfunction, or any and all | |
169 | other commercial damages or losses), even if such Contributor | |
170 | has been advised of the possibility of such damages. | |
171 | ||
172 | 9. Accepting Warranty or Additional Liability. While redistributing | |
173 | the Work or Derivative Works thereof, You may choose to offer, | |
174 | and charge a fee for, acceptance of support, warranty, indemnity, | |
175 | or other liability obligations and/or rights consistent with this | |
176 | License. However, in accepting such obligations, You may act only | |
177 | on Your own behalf and on Your sole responsibility, not on behalf | |
178 | of any other Contributor, and only if You agree to indemnify, | |
179 | defend, and hold each Contributor harmless for any liability | |
180 | incurred by, or claims asserted against, such Contributor by reason | |
181 | of your accepting any such warranty or additional liability. | |
182 | ||
183 | END OF TERMS AND CONDITIONS | |
184 | ||
185 | APPENDIX: How to apply the Apache License to your work. | |
186 | ||
187 | To apply the Apache License to your work, attach the following | |
188 | boilerplate notice, with the fields enclosed by brackets "[]" | |
189 | replaced with your own identifying information. (Don't include | |
190 | the brackets!) The text should be enclosed in the appropriate | |
191 | comment syntax for the file format. We also recommend that a | |
192 | file or class name and description of purpose be included on the | |
193 | same "printed page" as the copyright notice for easier | |
194 | identification within third-party archives. | |
195 | ||
196 | Copyright [yyyy] [name of copyright owner] | |
197 | ||
198 | Licensed under the Apache License, Version 2.0 (the "License"); | |
199 | you may not use this file except in compliance with the License. | |
200 | You may obtain a copy of the License at | |
201 | ||
202 | http://www.apache.org/licenses/LICENSE-2.0 | |
203 | ||
204 | Unless required by applicable law or agreed to in writing, software | |
205 | distributed under the License is distributed on an "AS IS" BASIS, | |
206 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
207 | See the License for the specific language governing permissions and | |
208 | limitations under the License. | |
209 | ||
210 | Project-URL: url, https://github.com/google/yapf | |
211 | Project-URL: changelog, https://github.com/google/yapf/blob/main/CHANGELOG.md | |
212 | Classifier: Development Status :: 4 - Beta | |
213 | Classifier: Environment :: Console | |
214 | Classifier: Intended Audience :: Developers | |
215 | Classifier: License :: OSI Approved :: Apache Software License | |
216 | Classifier: Operating System :: OS Independent | |
217 | Classifier: Programming Language :: Python | |
218 | Classifier: Programming Language :: Python :: 3 :: Only | |
219 | Classifier: Programming Language :: Python :: 3.7 | |
220 | Classifier: Programming Language :: Python :: 3.8 | |
221 | Classifier: Programming Language :: Python :: 3.9 | |
222 | Classifier: Programming Language :: Python :: 3.10 | |
223 | Classifier: Programming Language :: Python :: 3.11 | |
224 | Classifier: Topic :: Software Development :: Libraries :: Python Modules | |
225 | Classifier: Topic :: Software Development :: Quality Assurance | |
226 | Requires-Python: >=3.7 | |
227 | Description-Content-Type: text/markdown | |
228 | License-File: LICENSE | |
229 | License-File: AUTHORS | |
230 | Requires-Dist: importlib-metadata >=6.6.0 | |
231 | Requires-Dist: platformdirs >=3.5.1 | |
232 | Requires-Dist: tomli >=2.0.1 | |
233 | ||
234 | # YAPF | |
235 | ||
236 | <p align="center"> | |
237 | <a href="https://badge.fury.io/py/yapf"><img alt="PyPI Version" src="https://badge.fury.io/py/yapf.svg"></a> | |
238 | <a href="https://github.com/google/yapf/actions/workflows/ci.yml"><img alt="Build Status" src="https://github.com/google/yapf/actions/workflows/ci.yml/badge.svg"></a> | |
239 | <a href="https://github.com/google/yapf/actions/workflows/pre-commit.yml"><img alt="Actions Status" src="https://github.com/google/yapf/actions/workflows/pre-commit.yml/badge.svg"></a> | |
240 | <a href="https://coveralls.io/github/google/yapf?branch=main"><img alt="Coverage Status" src="https://coveralls.io/repos/github/google/yapf/badge.svg?branch=main"></a> | |
241 | </p> | |
242 | ||
243 | ||
244 | ## Introduction | |
245 | ||
246 | YAPF is a Python formatter based off of [`clang-format`](https://clang.llvm.org/docs/ClangFormat.html) | |
247 | (developed by Daniel Jasper). In essence, the algorithm takes the code and | |
248 | calculates the best formatting that conforms to the configured style. It takes | |
249 | away a lot of the drudgery of maintaining your code. | |
250 | ||
251 | The ultimate goal is that the code YAPF produces is as good as the code that a | |
252 | programmer would write if they were following the style guide. | |
253 | ||
254 | > **Note** | |
255 | > YAPF is not an official Google product (experimental or otherwise), it is | |
256 | > just code that happens to be owned by Google. | |
257 | ||
258 | ||
259 | ## Installation | |
260 | ||
261 | To install YAPF from PyPI: | |
262 | ||
263 | ```bash | |
264 | $ pip install yapf | |
265 | ``` | |
266 | ||
267 | YAPF is still considered in "beta" stage, and the released version may change | |
268 | often; therefore, the best way to keep up-to-date with the latest development | |
269 | is to clone this repository. | |
270 | ||
271 | Note that if you intend to use YAPF as a command-line tool rather than as a | |
272 | library, installation is not necessary. YAPF supports being run as a directory | |
273 | by the Python interpreter. If you cloned/unzipped YAPF into `DIR`, it's | |
274 | possible to run: | |
275 | ||
276 | ```bash | |
277 | $ PYTHONPATH=DIR python DIR/yapf [options] ... | |
278 | ``` | |
279 | ||
280 | ||
281 | ## Required Python versions | |
282 | ||
283 | YAPF supports Python 3.7+. | |
284 | ||
285 | > **Note** | |
286 | > YAPF requires the code it formats to be valid Python for the version YAPF | |
287 | > itself runs under. | |
288 | ||
289 | ||
290 | ## Usage | |
291 | ||
292 | ```console | |
293 | usage: yapf [-h] [-v] [-d | -i | -q] [-r | -l START-END] [-e PATTERN] | |
294 | [--style STYLE] [--style-help] [--no-local-style] [-p] [-m] [-vv] | |
295 | [files ...] | |
296 | ||
297 | Formatter for Python code. | |
298 | ||
299 | positional arguments: | |
300 | files reads from stdin when no files are specified. | |
301 | ||
302 | optional arguments: | |
303 | -h, --help show this help message and exit | |
304 | -v, --version show program's version number and exit | |
305 | -d, --diff print the diff for the fixed source | |
306 | -i, --in-place make changes to files in place | |
307 | -q, --quiet output nothing and set return value | |
308 | -r, --recursive run recursively over directories | |
309 | -l START-END, --lines START-END | |
310 | range of lines to reformat, one-based | |
311 | -e PATTERN, --exclude PATTERN | |
312 | patterns for files to exclude from formatting | |
313 | --style STYLE specify formatting style: either a style name (for | |
314 | example "pep8" or "google"), or the name of a file | |
315 | with style settings. The default is pep8 unless a | |
316 | .style.yapf or setup.cfg or pyproject.toml file | |
317 | located in the same directory as the source or one of | |
318 | its parent directories (for stdin, the current | |
319 | directory is used). | |
320 | --style-help show style settings and exit; this output can be saved | |
321 | to .style.yapf to make your settings permanent | |
322 | --no-local-style don't search for local style definition | |
323 | -p, --parallel run YAPF in parallel when formatting multiple files. | |
324 | -m, --print-modified print out file names of modified files | |
325 | -vv, --verbose print out file names while processing | |
326 | ``` | |
327 | ||
328 | ### Using YAPF within your favorite editor | |
329 | YAPF is supported by multiple editors via community extensions or plugins. See [Editor Support](EDITOR%20SUPPORT.md) for more info. | |
330 | ||
331 | ### Return Codes | |
332 | ||
333 | Normally YAPF returns zero on successful program termination and non-zero | |
334 | otherwise. | |
335 | ||
336 | If `--diff` is supplied, YAPF returns zero when no changes were necessary, | |
337 | non-zero otherwise (including program error). You can use this in a CI workflow | |
338 | to test that code has been YAPF-formatted. | |
339 | ||
340 | ### Excluding files from formatting (.yapfignore or pyproject.toml) | |
341 | ||
342 | In addition to exclude patterns provided on commandline, YAPF looks for | |
343 | additional patterns specified in a file named `.yapfignore` or `pyproject.toml` | |
344 | located in the working directory from which YAPF is invoked. | |
345 | ||
346 | `.yapfignore`'s syntax is similar to UNIX's filename pattern matching: | |
347 | ||
348 | ``` | |
349 | * matches everything | |
350 | ? matches any single character | |
351 | [seq] matches any character in seq | |
352 | [!seq] matches any character not in seq | |
353 | ``` | |
354 | ||
355 | Note that no entry should begin with `./`. | |
356 | ||
357 | If you use `pyproject.toml`, exclude patterns are specified by `ignore_patterns` key | |
358 | in `[tool.yapfignore]` section. For example: | |
359 | ||
360 | ```ini | |
361 | [tool.yapfignore] | |
362 | ignore_patterns = [ | |
363 | "temp/**/*.py", | |
364 | "temp2/*.py" | |
365 | ] | |
366 | ``` | |
367 | ||
368 | ||
369 | Formatting style | |
370 | ================ | |
371 | ||
372 | The formatting style used by YAPF is configurable and there are many "knobs" | |
373 | that can be used to tune how YAPF does formatting. See the `style.py` module | |
374 | for the full list. | |
375 | ||
376 | To control the style, run YAPF with the `--style` argument. It accepts one of | |
377 | the predefined styles (e.g., `pep8` or `google`), a path to a configuration | |
378 | file that specifies the desired style, or a dictionary of key/value pairs. | |
379 | ||
380 | The config file is a simple listing of (case-insensitive) `key = value` pairs | |
381 | with a `[style]` heading. For example: | |
382 | ||
383 | ```ini | |
384 | [style] | |
385 | based_on_style = pep8 | |
386 | spaces_before_comment = 4 | |
387 | split_before_logical_operator = true | |
388 | ``` | |
389 | ||
390 | The `based_on_style` setting determines which of the predefined styles this | |
391 | custom style is based on (think of it like subclassing). Four | |
392 | styles are predefined: | |
393 | ||
394 | - `pep8` (default) | |
395 | - `google` (based off of the [Google Python Style Guide](https://github.com/google/styleguide/blob/gh-pages/pyguide.md)) | |
396 | - `yapf` (for use with Google open source projects) | |
397 | - `facebook` | |
398 | ||
399 | See `_STYLE_NAME_TO_FACTORY` in [`style.py`](https://github.com/google/yapf/blob/main/yapf/yapflib/style.py) for details. | |
400 | ||
401 | It's also possible to do the same on the command line with a dictionary. For | |
402 | example: | |
403 | ||
404 | ```bash | |
405 | --style='{based_on_style: pep8, indent_width: 2}' | |
406 | ``` | |
407 | ||
408 | This will take the `pep8` base style and modify it to have two space | |
409 | indentations. | |
410 | ||
411 | YAPF will search for the formatting style in the following manner: | |
412 | ||
413 | 1. Specified on the command line | |
414 | 2. In the `[style]` section of a `.style.yapf` file in either the current | |
415 | directory or one of its parent directories. | |
416 | 3. In the `[yapf]` section of a `setup.cfg` file in either the current | |
417 | directory or one of its parent directories. | |
418 | 4. In the `[tool.yapf]` section of a `pyproject.toml` file in either the current | |
419 | directory or one of its parent directories. | |
420 | 5. In the `[style]` section of a `~/.config/yapf/style` file in your home | |
421 | directory. | |
422 | ||
423 | If none of those files are found, the default style PEP8 is used. | |
424 | ||
425 | ||
426 | Example | |
427 | ======= | |
428 | ||
429 | An example of the type of formatting that YAPF can do, it will take this ugly | |
430 | code: | |
431 | ||
432 | ```python | |
433 | x = { 'a':37,'b':42, | |
434 | ||
435 | 'c':927} | |
436 | ||
437 | y = 'hello ''world' | |
438 | z = 'hello '+'world' | |
439 | a = 'hello {}'.format('world') | |
440 | class foo ( object ): | |
441 | def f (self ): | |
442 | return 37*-+2 | |
443 | def g(self, x,y=42): | |
444 | return y | |
445 | def f ( a ) : | |
446 | return 37+-+a[42-x : y**3] | |
447 | ``` | |
448 | ||
449 | and reformat it into: | |
450 | ||
451 | ```python | |
452 | x = {'a': 37, 'b': 42, 'c': 927} | |
453 | ||
454 | y = 'hello ' 'world' | |
455 | z = 'hello ' + 'world' | |
456 | a = 'hello {}'.format('world') | |
457 | ||
458 | ||
459 | class foo(object): | |
460 | def f(self): | |
461 | return 37 * -+2 | |
462 | ||
463 | def g(self, x, y=42): | |
464 | return y | |
465 | ||
466 | ||
467 | def f(a): | |
468 | return 37 + -+a[42 - x:y**3] | |
469 | ``` | |
470 | ||
471 | ||
472 | ## Example as a module | |
473 | ||
474 | The two main APIs for calling YAPF are `FormatCode` and `FormatFile`, these | |
475 | share several arguments which are described below: | |
476 | ||
477 | ```python | |
478 | >>> from yapf.yapflib.yapf_api import FormatCode # reformat a string of code | |
479 | ||
480 | >>> formatted_code, changed = FormatCode("f ( a = 1, b = 2 )") | |
481 | >>> formatted_code | |
482 | 'f(a=1, b=2)\n' | |
483 | >>> changed | |
484 | True | |
485 | ``` | |
486 | ||
487 | A `style_config` argument: Either a style name or a path to a file that | |
488 | contains formatting style settings. If None is specified, use the default style | |
489 | as set in `style.DEFAULT_STYLE_FACTORY`. | |
490 | ||
491 | ```python | |
492 | >>> FormatCode("def g():\n return True", style_config='pep8')[0] | |
493 | 'def g():\n return True\n' | |
494 | ``` | |
495 | ||
496 | A `lines` argument: A list of tuples of lines (ints), [start, end], that we | |
497 | want to format. The lines are 1-based indexed. It can be used by third-party | |
498 | code (e.g., IDEs) when reformatting a snippet of code rather than a whole file. | |
499 | ||
500 | ```python | |
501 | >>> FormatCode("def g( ):\n a=1\n b = 2\n return a==b", lines=[(1, 1), (2, 3)])[0] | |
502 | 'def g():\n a = 1\n b = 2\n return a==b\n' | |
503 | ``` | |
504 | ||
505 | A `print_diff` (bool): Instead of returning the reformatted source, return a | |
506 | diff that turns the formatted source into reformatted source. | |
507 | ||
508 | ```diff | |
509 | >>> print(FormatCode("a==b", filename="foo.py", print_diff=True)[0]) | |
510 | --- foo.py (original) | |
511 | +++ foo.py (reformatted) | |
512 | @@ -1 +1 @@ | |
513 | -a==b | |
514 | +a == b | |
515 | ``` | |
516 | ||
517 | Note: the `filename` argument for `FormatCode` is what is inserted into the | |
518 | diff, the default is `<unknown>`. | |
519 | ||
520 | `FormatFile` returns reformatted code from the passed file along with its encoding: | |
521 | ||
522 | ```python | |
523 | >>> from yapf.yapflib.yapf_api import FormatFile # reformat a file | |
524 | ||
525 | >>> print(open("foo.py").read()) # contents of file | |
526 | a==b | |
527 | ||
528 | >>> reformatted_code, encoding, changed = FormatFile("foo.py") | |
529 | >>> formatted_code | |
530 | 'a == b\n' | |
531 | >>> encoding | |
532 | 'utf-8' | |
533 | >>> changed | |
534 | True | |
535 | ``` | |
536 | ||
537 | The `in_place` argument saves the reformatted code back to the file: | |
538 | ||
539 | ```python | |
540 | >>> FormatFile("foo.py", in_place=True)[:2] | |
541 | (None, 'utf-8') | |
542 | ||
543 | >>> print(open("foo.py").read()) # contents of file (now fixed) | |
544 | a == b | |
545 | ``` | |
546 | ||
547 | ||
548 | ## Formatting diffs | |
549 | ||
550 | Options: | |
551 | ||
552 | ```console | |
553 | usage: yapf-diff [-h] [-i] [-p NUM] [--regex PATTERN] [--iregex PATTERN][-v] | |
554 | [--style STYLE] [--binary BINARY] | |
555 | ||
556 | This script reads input from a unified diff and reformats all the changed | |
557 | lines. This is useful to reformat all the lines touched by a specific patch. | |
558 | Example usage for git/svn users: | |
559 | ||
560 | git diff -U0 --no-color --relative HEAD^ | yapf-diff -i | |
561 | svn diff --diff-cmd=diff -x-U0 | yapf-diff -p0 -i | |
562 | ||
563 | It should be noted that the filename contained in the diff is used | |
564 | unmodified to determine the source file to update. Users calling this script | |
565 | directly should be careful to ensure that the path in the diff is correct | |
566 | relative to the current working directory. | |
567 | ||
568 | optional arguments: | |
569 | -h, --help show this help message and exit | |
570 | -i, --in-place apply edits to files instead of displaying a diff | |
571 | -p NUM, --prefix NUM strip the smallest prefix containing P slashes | |
572 | --regex PATTERN custom pattern selecting file paths to reformat | |
573 | (case sensitive, overrides -iregex) | |
574 | --iregex PATTERN custom pattern selecting file paths to reformat | |
575 | (case insensitive, overridden by -regex) | |
576 | -v, --verbose be more verbose, ineffective without -i | |
577 | --style STYLE specify formatting style: either a style name (for | |
578 | example "pep8" or "google"), or the name of a file | |
579 | with style settings. The default is pep8 unless a | |
580 | .style.yapf or setup.cfg or pyproject.toml file | |
581 | located in the same directory as the source or one of | |
582 | its parent directories (for stdin, the current | |
583 | directory is used). | |
584 | --binary BINARY location of binary to use for YAPF | |
585 | ``` | |
586 | ||
587 | ||
588 | ## Knobs | |
589 | ||
590 | #### `ALIGN_CLOSING_BRACKET_WITH_VISUAL_INDENT` | |
591 | ||
592 | > Align closing bracket with visual indentation. | |
593 | ||
594 | #### `ALLOW_MULTILINE_LAMBDAS` | |
595 | ||
596 | > Allow lambdas to be formatted on more than one line. | |
597 | ||
598 | #### `ALLOW_MULTILINE_DICTIONARY_KEYS` | |
599 | ||
600 | > Allow dictionary keys to exist on multiple lines. For example: | |
601 | ||
602 | ```python | |
603 | x = { | |
604 | ('this is the first element of a tuple', | |
605 | 'this is the second element of a tuple'): | |
606 | value, | |
607 | } | |
608 | ``` | |
609 | ||
610 | #### `ALLOW_SPLIT_BEFORE_DEFAULT_OR_NAMED_ASSIGNS` | |
611 | ||
612 | > Allow splitting before a default / named assignment in an argument list. | |
613 | ||
614 | #### `ALLOW_SPLIT_BEFORE_DICT_VALUE` | |
615 | ||
616 | > Allow splits before the dictionary value. | |
617 | ||
618 | #### `ARITHMETIC_PRECEDENCE_INDICATION` | |
619 | ||
620 | > Let spacing indicate operator precedence. For example: | |
621 | ||
622 | ```python | |
623 | a = 1 * 2 + 3 / 4 | |
624 | b = 1 / 2 - 3 * 4 | |
625 | c = (1 + 2) * (3 - 4) | |
626 | d = (1 - 2) / (3 + 4) | |
627 | e = 1 * 2 - 3 | |
628 | f = 1 + 2 + 3 + 4 | |
629 | ``` | |
630 | ||
631 | > will be formatted as follows to indicate precedence: | |
632 | ||
633 | ```python | |
634 | a = 1*2 + 3/4 | |
635 | b = 1/2 - 3*4 | |
636 | c = (1+2) * (3-4) | |
637 | d = (1-2) / (3+4) | |
638 | e = 1*2 - 3 | |
639 | f = 1 + 2 + 3 + 4 | |
640 | ``` | |
641 | ||
642 | #### `BLANK_LINES_AROUND_TOP_LEVEL_DEFINITION` | |
643 | ||
644 | > Sets the number of desired blank lines surrounding top-level function and | |
645 | > class definitions. For example: | |
646 | ||
647 | ```python | |
648 | class Foo: | |
649 | pass | |
650 | # <------ having two blank lines here | |
651 | # <------ is the default setting | |
652 | class Bar: | |
653 | pass | |
654 | ``` | |
655 | ||
656 | #### `BLANK_LINE_BEFORE_CLASS_DOCSTRING` | |
657 | ||
658 | > Insert a blank line before a class-level docstring. | |
659 | ||
660 | #### `BLANK_LINE_BEFORE_MODULE_DOCSTRING` | |
661 | ||
662 | > Insert a blank line before a module docstring. | |
663 | ||
664 | #### `BLANK_LINE_BEFORE_NESTED_CLASS_OR_DEF` | |
665 | ||
666 | > Insert a blank line before a `def` or `class` immediately nested within | |
667 | > another `def` or `class`. For example: | |
668 | ||
669 | ```python | |
670 | class Foo: | |
671 | # <------ this blank line | |
672 | def method(): | |
673 | pass | |
674 | ``` | |
675 | ||
676 | #### `BLANK_LINES_BETWEEN_TOP_LEVEL_IMPORTS_AND_VARIABLES` | |
677 | ||
678 | > Sets the number of desired blank lines between top-level imports and | |
679 | > variable definitions. Useful for compatibility with tools like isort. | |
680 | ||
681 | #### `COALESCE_BRACKETS` | |
682 | ||
683 | > Do not split consecutive brackets. Only relevant when | |
684 | > `DEDENT_CLOSING_BRACKETS` or `INDENT_CLOSING_BRACKETS` is set. For example: | |
685 | ||
686 | ```python | |
687 | call_func_that_takes_a_dict( | |
688 | { | |
689 | 'key1': 'value1', | |
690 | 'key2': 'value2', | |
691 | } | |
692 | ) | |
693 | ``` | |
694 | ||
695 | > would reformat to: | |
696 | ||
697 | ```python | |
698 | call_func_that_takes_a_dict({ | |
699 | 'key1': 'value1', | |
700 | 'key2': 'value2', | |
701 | }) | |
702 | ``` | |
703 | ||
704 | #### `COLUMN_LIMIT` | |
705 | ||
706 | > The column limit (or max line-length) | |
707 | ||
708 | #### `CONTINUATION_ALIGN_STYLE` | |
709 | ||
710 | > The style for continuation alignment. Possible values are: | |
711 | ||
712 | > - `SPACE`: Use spaces for continuation alignment. This is default | |
713 | > behavior. | |
714 | > - `FIXED`: Use fixed number (`CONTINUATION_INDENT_WIDTH`) of columns | |
715 | > (i.e. `CONTINUATION_INDENT_WIDTH`/`INDENT_WIDTH` tabs or | |
716 | > `CONTINUATION_INDENT_WIDTH` spaces) for continuation alignment. | |
717 | > - `VALIGN-RIGHT`: Vertically align continuation lines to multiple of | |
718 | > `INDENT_WIDTH` columns. Slightly right (one tab or a few spaces) if cannot | |
719 | > vertically align continuation lines with indent characters. | |
720 | ||
721 | #### `CONTINUATION_INDENT_WIDTH` | |
722 | ||
723 | > Indent width used for line continuations. | |
724 | ||
725 | #### `DEDENT_CLOSING_BRACKETS` | |
726 | ||
727 | > Put closing brackets on a separate line, dedented, if the bracketed | |
728 | > expression can't fit in a single line. Applies to all kinds of brackets, | |
729 | > including function definitions and calls. For example: | |
730 | ||
731 | ```python | |
732 | config = { | |
733 | 'key1': 'value1', | |
734 | 'key2': 'value2', | |
735 | } # <--- this bracket is dedented and on a separate line | |
736 | ||
737 | time_series = self.remote_client.query_entity_counters( | |
738 | entity='dev3246.region1', | |
739 | key='dns.query_latency_tcp', | |
740 | transform=Transformation.AVERAGE(window=timedelta(seconds=60)), | |
741 | start_ts=now()-timedelta(days=3), | |
742 | end_ts=now(), | |
743 | ) # <--- this bracket is dedented and on a separate line | |
744 | ``` | |
745 | ||
746 | #### `DISABLE_ENDING_COMMA_HEURISTIC` | |
747 | ||
748 | > Disable the heuristic which places each list element on a separate line if | |
749 | > the list is comma-terminated. | |
750 | ||
751 | #### `EACH_DICT_ENTRY_ON_SEPARATE_LINE` | |
752 | ||
753 | > Place each dictionary entry onto its own line. | |
754 | ||
755 | #### `FORCE_MULTILINE_DICT` | |
756 | ||
757 | > Respect `EACH_DICT_ENTRY_ON_SEPARATE_LINE` even if the line is shorter than | |
758 | > `COLUMN_LIMIT`. | |
759 | ||
760 | #### `I18N_COMMENT` | |
761 | ||
762 | > The regex for an internationalization comment. The presence of this comment | |
763 | > stops reformatting of that line, because the comments are required to be | |
764 | > next to the string they translate. | |
765 | ||
766 | #### `I18N_FUNCTION_CALL` | |
767 | ||
768 | > The internationalization function call names. The presence of this function | |
769 | > stops reformatting on that line, because the string it has cannot be moved | |
770 | > away from the i18n comment. | |
771 | ||
772 | #### `INDENT_BLANK_LINES` | |
773 | ||
774 | > Set to `True` to prefer indented blank lines rather than empty | |
775 | ||
776 | #### `INDENT_CLOSING_BRACKETS` | |
777 | ||
778 | > Put closing brackets on a separate line, indented, if the bracketed | |
779 | > expression can't fit in a single line. Applies to all kinds of brackets, | |
780 | > including function definitions and calls. For example: | |
781 | ||
782 | ```python | |
783 | config = { | |
784 | 'key1': 'value1', | |
785 | 'key2': 'value2', | |
786 | } # <--- this bracket is indented and on a separate line | |
787 | ||
788 | time_series = self.remote_client.query_entity_counters( | |
789 | entity='dev3246.region1', | |
790 | key='dns.query_latency_tcp', | |
791 | transform=Transformation.AVERAGE(window=timedelta(seconds=60)), | |
792 | start_ts=now()-timedelta(days=3), | |
793 | end_ts=now(), | |
794 | ) # <--- this bracket is indented and on a separate line | |
795 | ``` | |
796 | ||
797 | #### `INDENT_DICTIONARY_VALUE` | |
798 | ||
799 | > Indent the dictionary value if it cannot fit on the same line as the | |
800 | > dictionary key. For example: | |
801 | ||
802 | ```python | |
803 | config = { | |
804 | 'key1': | |
805 | 'value1', | |
806 | 'key2': value1 + | |
807 | value2, | |
808 | } | |
809 | ``` | |
810 | ||
811 | #### `INDENT_WIDTH` | |
812 | ||
813 | > The number of columns to use for indentation. | |
814 | ||
815 | #### `JOIN_MULTIPLE_LINES` | |
816 | ||
817 | > Join short lines into one line. E.g., single line `if` statements. | |
818 | ||
819 | #### `NO_SPACES_AROUND_SELECTED_BINARY_OPERATORS` | |
820 | ||
821 | > Do not include spaces around selected binary operators. For example: | |
822 | ||
823 | ```python | |
824 | 1 + 2 * 3 - 4 / 5 | |
825 | ``` | |
826 | ||
827 | > will be formatted as follows when configured with `*`, `/`: | |
828 | ||
829 | ```python | |
830 | 1 + 2*3 - 4/5 | |
831 | ``` | |
832 | ||
833 | #### `SPACE_BETWEEN_ENDING_COMMA_AND_CLOSING_BRACKET` | |
834 | ||
835 | > Insert a space between the ending comma and closing bracket of a list, etc. | |
836 | ||
837 | #### `SPACE_INSIDE_BRACKETS` | |
838 | ||
839 | Use spaces inside brackets, braces, and parentheses. For example: | |
840 | ||
841 | ```python | |
842 | method_call( 1 ) | |
843 | my_dict[ 3 ][ 1 ][ get_index( *args, **kwargs ) ] | |
844 | my_set = { 1, 2, 3 } | |
845 | ``` | |
846 | ||
847 | #### `SPACES_AROUND_DEFAULT_OR_NAMED_ASSIGN` | |
848 | ||
849 | > Set to `True` to prefer spaces around the assignment operator for default | |
850 | > or keyword arguments. | |
851 | ||
852 | #### `SPACES_AROUND_DICT_DELIMITERS` | |
853 | ||
854 | > Adds a space after the opening '{' and before the ending '}' dict delimiters. | |
855 | ||
856 | ```python | |
857 | {1: 2} | |
858 | ``` | |
859 | ||
860 | > will be formatted as: | |
861 | ||
862 | ```python | |
863 | { 1: 2 } | |
864 | ``` | |
865 | ||
866 | #### `SPACES_AROUND_LIST_DELIMITERS` | |
867 | ||
868 | > Adds a space after the opening '[' and before the ending ']' list delimiters. | |
869 | ||
870 | ```python | |
871 | [1, 2] | |
872 | ``` | |
873 | ||
874 | > will be formatted as: | |
875 | ||
876 | ```python | |
877 | [ 1, 2 ] | |
878 | ``` | |
879 | ||
880 | #### `SPACES_AROUND_POWER_OPERATOR` | |
881 | ||
882 | > Set to `True` to prefer using spaces around `**`. | |
883 | ||
884 | #### `SPACES_AROUND_SUBSCRIPT_COLON` | |
885 | ||
886 | > Use spaces around the subscript / slice operator. For example: | |
887 | ||
888 | ```python | |
889 | my_list[1 : 10 : 2] | |
890 | ``` | |
891 | ||
892 | ##### `SPACES_AROUND_TUPLE_DELIMITERS` | |
893 | ||
894 | > Adds a space after the opening '(' and before the ending ')' tuple delimiters. | |
895 | ||
896 | ```python | |
897 | (1, 2, 3) | |
898 | ``` | |
899 | ||
900 | > will be formatted as: | |
901 | ||
902 | ```python | |
903 | ( 1, 2, 3 ) | |
904 | ``` | |
905 | ||
906 | #### `SPACES_BEFORE_COMMENT` | |
907 | ||
908 | > The number of spaces required before a trailing comment. | |
909 | > This can be a single value (representing the number of spaces | |
910 | > before each trailing comment) or list of values (representing | |
911 | > alignment column values; trailing comments within a block will | |
912 | > be aligned to the first column value that is greater than the maximum | |
913 | > line length within the block). | |
914 | ||
915 | > **Note:** Lists of values may need to be quoted in some contexts | |
916 | > (eg. shells or editor config files). | |
917 | ||
918 | > For example, with `spaces_before_comment=5`: | |
919 | ||
920 | ```python | |
921 | 1 + 1 # Adding values | |
922 | ``` | |
923 | ||
924 | > will be formatted as: | |
925 | ||
926 | ```python | |
927 | 1 + 1 # Adding values <-- 5 spaces between the end of the statement and comment | |
928 | ``` | |
929 | ||
930 | > with `spaces_before_comment="15, 20"`: | |
931 | ||
932 | ```python | |
933 | 1 + 1 # Adding values | |
934 | two + two # More adding | |
935 | ||
936 | longer_statement # This is a longer statement | |
937 | short # This is a shorter statement | |
938 | ||
939 | a_very_long_statement_that_extends_beyond_the_final_column # Comment | |
940 | short # This is a shorter statement | |
941 | ``` | |
942 | ||
943 | > will be formatted as: | |
944 | ||
945 | ```python | |
946 | 1 + 1 # Adding values <-- end of line comments in block aligned to col 15 | |
947 | two + two # More adding | |
948 | ||
949 | longer_statement # This is a longer statement <-- end of line comments in block aligned to col 20 | |
950 | short # This is a shorter statement | |
951 | ||
952 | a_very_long_statement_that_extends_beyond_the_final_column # Comment <-- the end of line comments are aligned based on the line length | |
953 | short # This is a shorter statement | |
954 | ``` | |
955 | ||
956 | #### `SPLIT_ALL_COMMA_SEPARATED_VALUES` | |
957 | ||
958 | > If a comma separated list (`dict`, `list`, `tuple`, or function `def`) is | |
959 | > on a line that is too long, split such that each element is on a separate | |
960 | > line. | |
961 | ||
962 | #### `SPLIT_ALL_TOP_LEVEL_COMMA_SEPARATED_VALUES` | |
963 | ||
964 | > Variation on `SPLIT_ALL_COMMA_SEPARATED_VALUES` in which, if a | |
965 | > subexpression with a comma fits in its starting line, then the | |
966 | > subexpression is not split. This avoids splits like the one for | |
967 | > `b` in this code: | |
968 | ||
969 | ```python | |
970 | abcdef( | |
971 | aReallyLongThing: int, | |
972 | b: [Int, | |
973 | Int]) | |
974 | ``` | |
975 | ||
976 | > with the new knob this is split as: | |
977 | ||
978 | ```python | |
979 | abcdef( | |
980 | aReallyLongThing: int, | |
981 | b: [Int, Int]) | |
982 | ``` | |
983 | ||
984 | #### `SPLIT_ARGUMENTS_WHEN_COMMA_TERMINATED` | |
985 | ||
986 | > Split before arguments if the argument list is terminated by a comma. | |
987 | ||
988 | #### `SPLIT_BEFORE_ARITHMETIC_OPERATOR` | |
989 | ||
990 | > Set to `True` to prefer splitting before `+`, `-`, `*`, `/`, `//`, or `@` | |
991 | > rather than after. | |
992 | ||
993 | #### `SPLIT_BEFORE_BITWISE_OPERATOR` | |
994 | ||
995 | > Set to `True` to prefer splitting before `&`, `|` or `^` rather than after. | |
996 | ||
997 | #### `SPLIT_BEFORE_CLOSING_BRACKET` | |
998 | ||
999 | > Split before the closing bracket if a `list` or `dict` literal doesn't fit | |
1000 | > on a single line. | |
1001 | ||
1002 | #### `SPLIT_BEFORE_DICT_SET_GENERATOR` | |
1003 | ||
1004 | > Split before a dictionary or set generator (`comp_for`). For example, note | |
1005 | > the split before the `for`: | |
1006 | ||
1007 | ```python | |
1008 | foo = { | |
1009 | variable: 'Hello world, have a nice day!' | |
1010 | for variable in bar if variable != 42 | |
1011 | } | |
1012 | ``` | |
1013 | ||
1014 | #### `SPLIT_BEFORE_DOT` | |
1015 | ||
1016 | > Split before the `.` if we need to split a longer expression: | |
1017 | ||
1018 | ```python | |
1019 | foo = ('This is a really long string: {}, {}, {}, {}'.format(a, b, c, d)) | |
1020 | ``` | |
1021 | ||
1022 | > would reformat to something like: | |
1023 | ||
1024 | ```python | |
1025 | foo = ('This is a really long string: {}, {}, {}, {}' | |
1026 | .format(a, b, c, d)) | |
1027 | ``` | |
1028 | ||
1029 | #### `SPLIT_BEFORE_EXPRESSION_AFTER_OPENING_PAREN` | |
1030 | ||
1031 | > Split after the opening paren which surrounds an expression if it doesn't | |
1032 | > fit on a single line. | |
1033 | ||
1034 | #### `SPLIT_BEFORE_FIRST_ARGUMENT` | |
1035 | ||
1036 | > If an argument / parameter list is going to be split, then split before the | |
1037 | > first argument. | |
1038 | ||
1039 | #### `SPLIT_BEFORE_LOGICAL_OPERATOR` | |
1040 | ||
1041 | > Set to `True` to prefer splitting before `and` or `or` rather than after. | |
1042 | ||
1043 | #### `SPLIT_BEFORE_NAMED_ASSIGNS` | |
1044 | ||
1045 | > Split named assignments onto individual lines. | |
1046 | ||
1047 | #### `SPLIT_COMPLEX_COMPREHENSION` | |
1048 | ||
1049 | > For list comprehensions and generator expressions with multiple clauses | |
1050 | > (e.g multiple `for` calls, `if` filter expressions) and which need to be | |
1051 | > reflowed, split each clause onto its own line. For example: | |
1052 | ||
1053 | ```python | |
1054 | result = [ | |
1055 | a_var + b_var for a_var in xrange(1000) for b_var in xrange(1000) | |
1056 | if a_var % b_var] | |
1057 | ``` | |
1058 | ||
1059 | > would reformat to something like: | |
1060 | ||
1061 | ```python | |
1062 | result = [ | |
1063 | a_var + b_var | |
1064 | for a_var in xrange(1000) | |
1065 | for b_var in xrange(1000) | |
1066 | if a_var % b_var] | |
1067 | ``` | |
1068 | ||
1069 | #### `SPLIT_PENALTY_AFTER_OPENING_BRACKET` | |
1070 | ||
1071 | > The penalty for splitting right after the opening bracket. | |
1072 | ||
1073 | #### `SPLIT_PENALTY_AFTER_UNARY_OPERATOR` | |
1074 | ||
1075 | > The penalty for splitting the line after a unary operator. | |
1076 | ||
1077 | #### `SPLIT_PENALTY_ARITHMETIC_OPERATOR` | |
1078 | ||
1079 | > The penalty of splitting the line around the `+`, `-`, `*`, `/`, `//`, `%`, | |
1080 | > and `@` operators. | |
1081 | ||
1082 | #### `SPLIT_PENALTY_BEFORE_IF_EXPR` | |
1083 | ||
1084 | > The penalty for splitting right before an `if` expression. | |
1085 | ||
1086 | #### `SPLIT_PENALTY_BITWISE_OPERATOR` | |
1087 | ||
1088 | > The penalty of splitting the line around the `&`, `|`, and `^` operators. | |
1089 | ||
1090 | #### `SPLIT_PENALTY_COMPREHENSION` | |
1091 | ||
1092 | > The penalty for splitting a list comprehension or generator expression. | |
1093 | ||
1094 | #### `SPLIT_PENALTY_EXCESS_CHARACTER` | |
1095 | ||
1096 | > The penalty for characters over the column limit. | |
1097 | ||
1098 | #### `SPLIT_PENALTY_FOR_ADDED_LINE_SPLIT` | |
1099 | ||
1100 | > The penalty incurred by adding a line split to the logical line. The more | |
1101 | > line splits added the higher the penalty. | |
1102 | ||
1103 | #### `SPLIT_PENALTY_IMPORT_NAMES` | |
1104 | ||
1105 | > The penalty of splitting a list of `import as` names. For example: | |
1106 | ||
1107 | ```python | |
1108 | from a_very_long_or_indented_module_name_yada_yad import (long_argument_1, | |
1109 | long_argument_2, | |
1110 | long_argument_3) | |
1111 | ``` | |
1112 | ||
1113 | > would reformat to something like: | |
1114 | ||
1115 | ```python | |
1116 | from a_very_long_or_indented_module_name_yada_yad import ( | |
1117 | long_argument_1, long_argument_2, long_argument_3) | |
1118 | ``` | |
1119 | ||
1120 | #### `SPLIT_PENALTY_LOGICAL_OPERATOR` | |
1121 | ||
1122 | > The penalty of splitting the line around the `and` and `or` operators. | |
1123 | ||
1124 | #### `USE_TABS` | |
1125 | ||
1126 | > Use the Tab character for indentation. | |
1127 | ||
1128 | ||
1129 | ## (Potentially) Frequently Asked Questions | |
1130 | ||
1131 | ### Why does YAPF destroy my awesome formatting? | |
1132 | ||
1133 | YAPF tries very hard to get the formatting correct. But for some code, it won't | |
1134 | be as good as hand-formatting. In particular, large data literals may become | |
1135 | horribly disfigured under YAPF. | |
1136 | ||
1137 | The reasons for this are manyfold. In short, YAPF is simply a tool to help | |
1138 | with development. It will format things to coincide with the style guide, but | |
1139 | that may not equate with readability. | |
1140 | ||
1141 | What can be done to alleviate this situation is to indicate regions YAPF should | |
1142 | ignore when reformatting something: | |
1143 | ||
1144 | ```python | |
1145 | # yapf: disable | |
1146 | FOO = { | |
1147 | # ... some very large, complex data literal. | |
1148 | } | |
1149 | ||
1150 | BAR = [ | |
1151 | # ... another large data literal. | |
1152 | ] | |
1153 | # yapf: enable | |
1154 | ``` | |
1155 | ||
1156 | You can also disable formatting for a single literal like this: | |
1157 | ||
1158 | ```python | |
1159 | BAZ = { | |
1160 | (1, 2, 3, 4), | |
1161 | (5, 6, 7, 8), | |
1162 | (9, 10, 11, 12), | |
1163 | } # yapf: disable | |
1164 | ``` | |
1165 | ||
1166 | To preserve the nice dedented closing brackets, use the | |
1167 | `dedent_closing_brackets` in your style. Note that in this case all | |
1168 | brackets, including function definitions and calls, are going to use | |
1169 | that style. This provides consistency across the formatted codebase. | |
1170 | ||
1171 | ### Why Not Improve Existing Tools? | |
1172 | ||
1173 | We wanted to use clang-format's reformatting algorithm. It's very powerful and | |
1174 | designed to come up with the best formatting possible. Existing tools were | |
1175 | created with different goals in mind, and would require extensive modifications | |
1176 | to convert to using clang-format's algorithm. | |
1177 | ||
1178 | ### Can I Use YAPF In My Program? | |
1179 | ||
1180 | Please do! YAPF was designed to be used as a library as well as a command line | |
1181 | tool. This means that a tool or IDE plugin is free to use YAPF. | |
1182 | ||
1183 | ### I still get non-PEP8 compliant code! Why? | |
1184 | ||
1185 | YAPF tries very hard to be fully PEP 8 compliant. However, it is paramount | |
1186 | to not risk altering the semantics of your code. Thus, YAPF tries to be as | |
1187 | safe as possible and does not change the token stream | |
1188 | (e.g., by adding parentheses). | |
1189 | All these cases however, can be easily fixed manually. For instance, | |
1190 | ||
1191 | ```python | |
1192 | from my_package import my_function_1, my_function_2, my_function_3, my_function_4, my_function_5 | |
1193 | ||
1194 | FOO = my_variable_1 + my_variable_2 + my_variable_3 + my_variable_4 + my_variable_5 + my_variable_6 + my_variable_7 + my_variable_8 | |
1195 | ``` | |
1196 | ||
1197 | won't be split, but you can easily get it right by just adding parentheses: | |
1198 | ||
1199 | ```python | |
1200 | from my_package import (my_function_1, my_function_2, my_function_3, | |
1201 | my_function_4, my_function_5) | |
1202 | ||
1203 | FOO = (my_variable_1 + my_variable_2 + my_variable_3 + my_variable_4 + | |
1204 | my_variable_5 + my_variable_6 + my_variable_7 + my_variable_8) | |
1205 | ``` | |
1206 | ||
1207 | ||
1208 | ## Gory Details | |
1209 | ||
1210 | ### Algorithm Design | |
1211 | ||
1212 | The main data structure in YAPF is the `LogicalLine` object. It holds a list | |
1213 | of `FormatToken`\s, that we would want to place on a single line if there | |
1214 | were no column limit. An exception being a comment in the middle of an | |
1215 | expression statement will force the line to be formatted on more than one line. | |
1216 | The formatter works on one `LogicalLine` object at a time. | |
1217 | ||
1218 | An `LogicalLine` typically won't affect the formatting of lines before or | |
1219 | after it. There is a part of the algorithm that may join two or more | |
1220 | `LogicalLine`\s into one line. For instance, an if-then statement with a | |
1221 | short body can be placed on a single line: | |
1222 | ||
1223 | ```python | |
1224 | if a == 42: continue | |
1225 | ``` | |
1226 | ||
1227 | YAPF's formatting algorithm creates a weighted tree that acts as the solution | |
1228 | space for the algorithm. Each node in the tree represents the result of a | |
1229 | formatting decision --- i.e., whether to split or not to split before a token. | |
1230 | Each formatting decision has a cost associated with it. Therefore, the cost is | |
1231 | realized on the edge between two nodes. (In reality, the weighted tree doesn't | |
1232 | have separate edge objects, so the cost resides on the nodes themselves.) | |
1233 | ||
1234 | For example, take the following Python code snippet. For the sake of this | |
1235 | example, assume that line (1) violates the column limit restriction and needs to | |
1236 | be reformatted. | |
1237 | ||
1238 | ```python | |
1239 | def xxxxxxxxxxx(aaaaaaaaaaaa, bbbbbbbbb, cccccccc, dddddddd, eeeeee): # 1 | |
1240 | pass # 2 | |
1241 | ``` | |
1242 | ||
1243 | For line (1), the algorithm will build a tree where each node (a | |
1244 | `FormattingDecisionState` object) is the state of the line at that token given | |
1245 | the decision to split before the token or not. Note: the `FormatDecisionState` | |
1246 | objects are copied by value so each node in the graph is unique and a change in | |
1247 | one doesn't affect other nodes. | |
1248 | ||
1249 | Heuristics are used to determine the costs of splitting or not splitting. | |
1250 | Because a node holds the state of the tree up to a token's insertion, it can | |
1251 | easily determine if a splitting decision will violate one of the style | |
1252 | requirements. For instance, the heuristic is able to apply an extra penalty to | |
1253 | the edge when not splitting between the previous token and the one being added. | |
1254 | ||
1255 | There are some instances where we will never want to split the line, because | |
1256 | doing so will always be detrimental (i.e., it will require a backslash-newline, | |
1257 | which is very rarely desirable). For line (1), we will never want to split the | |
1258 | first three tokens: `def`, `xxxxxxxxxxx`, and `(`. Nor will we want to | |
1259 | split between the `)` and the `:` at the end. These regions are said to be | |
1260 | "unbreakable." This is reflected in the tree by there not being a "split" | |
1261 | decision (left hand branch) within the unbreakable region. | |
1262 | ||
1263 | Now that we have the tree, we determine what the "best" formatting is by finding | |
1264 | the path through the tree with the lowest cost. | |
1265 | ||
1266 | And that's it! |