4 Summary: A formatter for Python code
6 Maintainer-email: Bill Wendling <morbo@google.com>
9 Version 2.0, January 2004
10 http://www.apache.org/licenses/
12 TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
16 "License" shall mean the terms and conditions for use, reproduction,
17 and distribution as defined by Sections 1 through 9 of this document.
19 "Licensor" shall mean the copyright owner or entity authorized by
20 the copyright owner that is granting the License.
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.
30 "You" (or "Your") shall mean an individual or Legal Entity
31 exercising permissions granted by this License.
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.
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.
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).
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.
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."
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.
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.
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.
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:
101 (a) You must give any other recipients of the Work or
102 Derivative Works a copy of this License; and
104 (b) You must cause any modified files to carry prominent notices
105 stating that You changed the files; and
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
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.
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.
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.
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.
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.
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.
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.
183 END OF TERMS AND CONDITIONS
185 APPENDIX: How to apply the Apache License to your work.
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.
196 Copyright [yyyy] [name of copyright owner]
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
202 http://www.apache.org/licenses/LICENSE-2.0
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.
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
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>
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.
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.
255 > YAPF is not an official Google product (experimental or otherwise), it is
256 > just code that happens to be owned by Google.
261 To install YAPF from PyPI:
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.
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
277 $ PYTHONPATH=DIR python DIR/yapf [options] ...
281 ## Required Python versions
283 YAPF supports Python 3.7+.
286 > YAPF requires the code it formats to be valid Python for the version YAPF
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]
297 Formatter for Python code.
299 positional arguments:
300 files reads from stdin when no files are specified.
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
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
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.
333 Normally YAPF returns zero on successful program termination and non-zero
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.
340 ### Excluding files from formatting (.yapfignore or pyproject.toml)
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.
346 `.yapfignore`'s syntax is similar to UNIX's filename pattern matching:
350 ? matches any single character
351 [seq] matches any character in seq
352 [!seq] matches any character not in seq
355 Note that no entry should begin with `./`.
357 If you use `pyproject.toml`, exclude patterns are specified by `ignore_patterns` key
358 in `[tool.yapfignore]` section. For example:
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
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.
380 The config file is a simple listing of (case-insensitive) `key = value` pairs
381 with a `[style]` heading. For example:
385 based_on_style = pep8
386 spaces_before_comment = 4
387 split_before_logical_operator = true
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:
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)
399 See `_STYLE_NAME_TO_FACTORY` in [`style.py`](https://github.com/google/yapf/blob/main/yapf/yapflib/style.py) for details.
401 It's also possible to do the same on the command line with a dictionary. For
405 --style='{based_on_style: pep8, indent_width: 2}'
408 This will take the `pep8` base style and modify it to have two space
411 YAPF will search for the formatting style in the following manner:
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
423 If none of those files are found, the default style PEP8 is used.
429 An example of the type of formatting that YAPF can do, it will take this ugly
439 a = 'hello {}'.format('world')
440 class foo ( object ):
446 return 37+-+a[42-x : y**3]
449 and reformat it into:
452 x = {'a': 37, 'b': 42, 'c': 927}
455 z = 'hello ' + 'world'
456 a = 'hello {}'.format('world')
463 def g(self, x, y=42):
468 return 37 + -+a[42 - x:y**3]
472 ## Example as a module
474 The two main APIs for calling YAPF are `FormatCode` and `FormatFile`, these
475 share several arguments which are described below:
478 >>> from yapf.yapflib.yapf_api import FormatCode # reformat a string of code
480 >>> formatted_code, changed = FormatCode("f ( a = 1, b = 2 )")
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`.
492 >>> FormatCode("def g():\n return True", style_config='pep8')[0]
493 'def g():\n return True\n'
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.
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'
505 A `print_diff` (bool): Instead of returning the reformatted source, return a
506 diff that turns the formatted source into reformatted source.
509 >>> print(FormatCode("a==b", filename="foo.py", print_diff=True)[0])
510 --- foo.py (original)
511 +++ foo.py (reformatted)
517 Note: the `filename` argument for `FormatCode` is what is inserted into the
518 diff, the default is `<unknown>`.
520 `FormatFile` returns reformatted code from the passed file along with its encoding:
523 >>> from yapf.yapflib.yapf_api import FormatFile # reformat a file
525 >>> print(open("foo.py").read()) # contents of file
528 >>> reformatted_code, encoding, changed = FormatFile("foo.py")
537 The `in_place` argument saves the reformatted code back to the file:
540 >>> FormatFile("foo.py", in_place=True)[:2]
543 >>> print(open("foo.py").read()) # contents of file (now fixed)
553 usage: yapf-diff [-h] [-i] [-p NUM] [--regex PATTERN] [--iregex PATTERN][-v]
554 [--style STYLE] [--binary BINARY]
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:
560 git diff -U0 --no-color --relative HEAD^ | yapf-diff -i
561 svn diff --diff-cmd=diff -x-U0 | yapf-diff -p0 -i
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.
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
584 --binary BINARY location of binary to use for YAPF
590 #### `ALIGN_CLOSING_BRACKET_WITH_VISUAL_INDENT`
592 > Align closing bracket with visual indentation.
594 #### `ALLOW_MULTILINE_LAMBDAS`
596 > Allow lambdas to be formatted on more than one line.
598 #### `ALLOW_MULTILINE_DICTIONARY_KEYS`
600 > Allow dictionary keys to exist on multiple lines. For example:
604 ('this is the first element of a tuple',
605 'this is the second element of a tuple'):
610 #### `ALLOW_SPLIT_BEFORE_DEFAULT_OR_NAMED_ASSIGNS`
612 > Allow splitting before a default / named assignment in an argument list.
614 #### `ALLOW_SPLIT_BEFORE_DICT_VALUE`
616 > Allow splits before the dictionary value.
618 #### `ARITHMETIC_PRECEDENCE_INDICATION`
620 > Let spacing indicate operator precedence. For example:
625 c = (1 + 2) * (3 - 4)
626 d = (1 - 2) / (3 + 4)
631 > will be formatted as follows to indicate precedence:
642 #### `BLANK_LINES_AROUND_TOP_LEVEL_DEFINITION`
644 > Sets the number of desired blank lines surrounding top-level function and
645 > class definitions. For example:
650 # <------ having two blank lines here
651 # <------ is the default setting
656 #### `BLANK_LINE_BEFORE_CLASS_DOCSTRING`
658 > Insert a blank line before a class-level docstring.
660 #### `BLANK_LINE_BEFORE_MODULE_DOCSTRING`
662 > Insert a blank line before a module docstring.
664 #### `BLANK_LINE_BEFORE_NESTED_CLASS_OR_DEF`
666 > Insert a blank line before a `def` or `class` immediately nested within
667 > another `def` or `class`. For example:
671 # <------ this blank line
676 #### `BLANK_LINES_BETWEEN_TOP_LEVEL_IMPORTS_AND_VARIABLES`
678 > Sets the number of desired blank lines between top-level imports and
679 > variable definitions. Useful for compatibility with tools like isort.
681 #### `COALESCE_BRACKETS`
683 > Do not split consecutive brackets. Only relevant when
684 > `DEDENT_CLOSING_BRACKETS` or `INDENT_CLOSING_BRACKETS` is set. For example:
687 call_func_that_takes_a_dict(
698 call_func_that_takes_a_dict({
706 > The column limit (or max line-length)
708 #### `CONTINUATION_ALIGN_STYLE`
710 > The style for continuation alignment. Possible values are:
712 > - `SPACE`: Use spaces for continuation alignment. This is default
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.
721 #### `CONTINUATION_INDENT_WIDTH`
723 > Indent width used for line continuations.
725 #### `DEDENT_CLOSING_BRACKETS`
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:
735 } # <--- this bracket is dedented and on a separate line
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),
743 ) # <--- this bracket is dedented and on a separate line
746 #### `DISABLE_ENDING_COMMA_HEURISTIC`
748 > Disable the heuristic which places each list element on a separate line if
749 > the list is comma-terminated.
751 #### `EACH_DICT_ENTRY_ON_SEPARATE_LINE`
753 > Place each dictionary entry onto its own line.
755 #### `FORCE_MULTILINE_DICT`
757 > Respect `EACH_DICT_ENTRY_ON_SEPARATE_LINE` even if the line is shorter than
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.
766 #### `I18N_FUNCTION_CALL`
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.
772 #### `INDENT_BLANK_LINES`
774 > Set to `True` to prefer indented blank lines rather than empty
776 #### `INDENT_CLOSING_BRACKETS`
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:
786 } # <--- this bracket is indented and on a separate line
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),
794 ) # <--- this bracket is indented and on a separate line
797 #### `INDENT_DICTIONARY_VALUE`
799 > Indent the dictionary value if it cannot fit on the same line as the
800 > dictionary key. For example:
813 > The number of columns to use for indentation.
815 #### `JOIN_MULTIPLE_LINES`
817 > Join short lines into one line. E.g., single line `if` statements.
819 #### `NO_SPACES_AROUND_SELECTED_BINARY_OPERATORS`
821 > Do not include spaces around selected binary operators. For example:
827 > will be formatted as follows when configured with `*`, `/`:
833 #### `SPACE_BETWEEN_ENDING_COMMA_AND_CLOSING_BRACKET`
835 > Insert a space between the ending comma and closing bracket of a list, etc.
837 #### `SPACE_INSIDE_BRACKETS`
839 Use spaces inside brackets, braces, and parentheses. For example:
843 my_dict[ 3 ][ 1 ][ get_index( *args, **kwargs ) ]
847 #### `SPACES_AROUND_DEFAULT_OR_NAMED_ASSIGN`
849 > Set to `True` to prefer spaces around the assignment operator for default
850 > or keyword arguments.
852 #### `SPACES_AROUND_DICT_DELIMITERS`
854 > Adds a space after the opening '{' and before the ending '}' dict delimiters.
860 > will be formatted as:
866 #### `SPACES_AROUND_LIST_DELIMITERS`
868 > Adds a space after the opening '[' and before the ending ']' list delimiters.
874 > will be formatted as:
880 #### `SPACES_AROUND_POWER_OPERATOR`
882 > Set to `True` to prefer using spaces around `**`.
884 #### `SPACES_AROUND_SUBSCRIPT_COLON`
886 > Use spaces around the subscript / slice operator. For example:
892 ##### `SPACES_AROUND_TUPLE_DELIMITERS`
894 > Adds a space after the opening '(' and before the ending ')' tuple delimiters.
900 > will be formatted as:
906 #### `SPACES_BEFORE_COMMENT`
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).
915 > **Note:** Lists of values may need to be quoted in some contexts
916 > (eg. shells or editor config files).
918 > For example, with `spaces_before_comment=5`:
921 1 + 1 # Adding values
924 > will be formatted as:
927 1 + 1 # Adding values <-- 5 spaces between the end of the statement and comment
930 > with `spaces_before_comment="15, 20"`:
933 1 + 1 # Adding values
934 two + two # More adding
936 longer_statement # This is a longer statement
937 short # This is a shorter statement
939 a_very_long_statement_that_extends_beyond_the_final_column # Comment
940 short # This is a shorter statement
943 > will be formatted as:
946 1 + 1 # Adding values <-- end of line comments in block aligned to col 15
947 two + two # More adding
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
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
956 #### `SPLIT_ALL_COMMA_SEPARATED_VALUES`
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
962 #### `SPLIT_ALL_TOP_LEVEL_COMMA_SEPARATED_VALUES`
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
971 aReallyLongThing: int,
976 > with the new knob this is split as:
980 aReallyLongThing: int,
984 #### `SPLIT_ARGUMENTS_WHEN_COMMA_TERMINATED`
986 > Split before arguments if the argument list is terminated by a comma.
988 #### `SPLIT_BEFORE_ARITHMETIC_OPERATOR`
990 > Set to `True` to prefer splitting before `+`, `-`, `*`, `/`, `//`, or `@`
993 #### `SPLIT_BEFORE_BITWISE_OPERATOR`
995 > Set to `True` to prefer splitting before `&`, `|` or `^` rather than after.
997 #### `SPLIT_BEFORE_CLOSING_BRACKET`
999 > Split before the closing bracket if a `list` or `dict` literal doesn't fit
1002 #### `SPLIT_BEFORE_DICT_SET_GENERATOR`
1004 > Split before a dictionary or set generator (`comp_for`). For example, note
1005 > the split before the `for`:
1009 variable: 'Hello world, have a nice day!'
1010 for variable in bar if variable != 42
1014 #### `SPLIT_BEFORE_DOT`
1016 > Split before the `.` if we need to split a longer expression:
1019 foo = ('This is a really long string: {}, {}, {}, {}'.format(a, b, c, d))
1022 > would reformat to something like:
1025 foo = ('This is a really long string: {}, {}, {}, {}'
1026 .format(a, b, c, d))
1029 #### `SPLIT_BEFORE_EXPRESSION_AFTER_OPENING_PAREN`
1031 > Split after the opening paren which surrounds an expression if it doesn't
1032 > fit on a single line.
1034 #### `SPLIT_BEFORE_FIRST_ARGUMENT`
1036 > If an argument / parameter list is going to be split, then split before the
1039 #### `SPLIT_BEFORE_LOGICAL_OPERATOR`
1041 > Set to `True` to prefer splitting before `and` or `or` rather than after.
1043 #### `SPLIT_BEFORE_NAMED_ASSIGNS`
1045 > Split named assignments onto individual lines.
1047 #### `SPLIT_COMPLEX_COMPREHENSION`
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:
1055 a_var + b_var for a_var in xrange(1000) for b_var in xrange(1000)
1059 > would reformat to something like:
1064 for a_var in xrange(1000)
1065 for b_var in xrange(1000)
1069 #### `SPLIT_PENALTY_AFTER_OPENING_BRACKET`
1071 > The penalty for splitting right after the opening bracket.
1073 #### `SPLIT_PENALTY_AFTER_UNARY_OPERATOR`
1075 > The penalty for splitting the line after a unary operator.
1077 #### `SPLIT_PENALTY_ARITHMETIC_OPERATOR`
1079 > The penalty of splitting the line around the `+`, `-`, `*`, `/`, `//`, `%`,
1080 > and `@` operators.
1082 #### `SPLIT_PENALTY_BEFORE_IF_EXPR`
1084 > The penalty for splitting right before an `if` expression.
1086 #### `SPLIT_PENALTY_BITWISE_OPERATOR`
1088 > The penalty of splitting the line around the `&`, `|`, and `^` operators.
1090 #### `SPLIT_PENALTY_COMPREHENSION`
1092 > The penalty for splitting a list comprehension or generator expression.
1094 #### `SPLIT_PENALTY_EXCESS_CHARACTER`
1096 > The penalty for characters over the column limit.
1098 #### `SPLIT_PENALTY_FOR_ADDED_LINE_SPLIT`
1100 > The penalty incurred by adding a line split to the logical line. The more
1101 > line splits added the higher the penalty.
1103 #### `SPLIT_PENALTY_IMPORT_NAMES`
1105 > The penalty of splitting a list of `import as` names. For example:
1108 from a_very_long_or_indented_module_name_yada_yad import (long_argument_1,
1113 > would reformat to something like:
1116 from a_very_long_or_indented_module_name_yada_yad import (
1117 long_argument_1, long_argument_2, long_argument_3)
1120 #### `SPLIT_PENALTY_LOGICAL_OPERATOR`
1122 > The penalty of splitting the line around the `and` and `or` operators.
1126 > Use the Tab character for indentation.
1129 ## (Potentially) Frequently Asked Questions
1131 ### Why does YAPF destroy my awesome formatting?
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.
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.
1141 What can be done to alleviate this situation is to indicate regions YAPF should
1142 ignore when reformatting something:
1147 # ... some very large, complex data literal.
1151 # ... another large data literal.
1156 You can also disable formatting for a single literal like this:
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.
1171 ### Why Not Improve Existing Tools?
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.
1178 ### Can I Use YAPF In My Program?
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.
1183 ### I still get non-PEP8 compliant code! Why?
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,
1192 from my_package import my_function_1, my_function_2, my_function_3, my_function_4, my_function_5
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
1197 won't be split, but you can easily get it right by just adding parentheses:
1200 from my_package import (my_function_1, my_function_2, my_function_3,
1201 my_function_4, my_function_5)
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)
1210 ### Algorithm Design
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.
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:
1224 if a == 42: continue
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.)
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
1239 def xxxxxxxxxxx(aaaaaaaaaaaa, bbbbbbbbb, cccccccc, dddddddd, eeeeee): # 1
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.
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.
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.
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.