• Home
Name Date Size #Lines LOC

..--

.github/04-Jul-2025-153119

.vscode/04-Jul-2025-5048

plugins/04-Jul-2025-267177

third_party/04-Jul-2025-5,0403,967

yapf/04-Jul-2025-10,0966,940

yapftests/04-Jul-2025-13,70011,459

.coveragercD04-Jul-202532 43

.editorconfigD04-Jul-2025265 1511

.flake8D04-Jul-2025408 1816

.gitattributesD04-Jul-202523 21

.gitignoreD04-Jul-20251.3 KiB4639

.isort.cfgD04-Jul-2025163 75

.pre-commit-config.yamlD04-Jul-2025913 3733

.pre-commit-hooks.yamlD04-Jul-2025602 2218

.python-versionD04-Jul-202535 65

.style.yapfD04-Jul-202530 32

.vimrcD04-Jul-2025167 54

AUTHORSD04-Jul-2025307 107

CHANGELOG.mdD04-Jul-202538.4 KiB888798

CONTRIBUTING.mdD04-Jul-20252 KiB5036

CONTRIBUTORSD04-Jul-2025685 1917

EDITOR SUPPORT.mdD04-Jul-20252.9 KiB8366

HACKING.mdD04-Jul-20251.7 KiB7653

LICENSED04-Jul-202511.1 KiB203169

MANIFEST.inD04-Jul-2025259 54

METADATAD04-Jul-2025505 2018

OWNERSD04-Jul-2025135 54

README.mdD04-Jul-202531.7 KiB1,072766

pylintrcD04-Jul-202512.8 KiB445323

pyproject.tomlD04-Jul-20252 KiB6455

tox.iniD04-Jul-2025356 2016

README.md

1# YAPF
2
3<p align="center">
4<a href="https://badge.fury.io/py/yapf"><img alt="PyPI Version" src="https://badge.fury.io/py/yapf.svg"></a>
5<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>
6<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>
7<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>
8</p>
9
10
11## Introduction
12
13YAPF is a Python formatter based on [`clang-format`](https://clang.llvm.org/docs/ClangFormat.html)
14(developed by Daniel Jasper). In essence, the algorithm takes the code and
15calculates the best formatting that conforms to the configured style. It takes
16away a lot of the drudgery of maintaining your code.
17
18The ultimate goal is that the code YAPF produces is as good as the code that a
19programmer would write if they were following the style guide.
20
21> **Note**
22> YAPF is not an official Google product (experimental or otherwise), it is
23> just code that happens to be owned by Google.
24
25
26## Installation
27
28To install YAPF from PyPI:
29
30```bash
31$ pip install yapf
32```
33
34YAPF is still considered in "beta" stage, and the released version may change
35often; therefore, the best way to keep up-to-date with the latest development
36is to clone this repository or install directly from github:
37
38```bash
39$ pip install git+https://github.com/google/yapf.git
40```
41
42Note that if you intend to use YAPF as a command-line tool rather than as a
43library, installation is not necessary. YAPF supports being run as a directory
44by the Python interpreter. If you cloned/unzipped YAPF into `DIR`, it's
45possible to run:
46
47```bash
48$ PYTHONPATH=DIR python DIR/yapf [options] ...
49```
50
51## Using YAPF within your favorite editor
52YAPF is supported by multiple editors via community extensions or plugins. See [Editor Support](EDITOR%20SUPPORT.md) for more info.
53
54## Required Python versions
55
56YAPF supports Python 3.7+.
57
58
59## Usage
60
61```console
62usage: yapf [-h] [-v] [-d | -i | -q] [-r | -l START-END] [-e PATTERN]
63            [--style STYLE] [--style-help] [--no-local-style] [-p] [-m] [-vv]
64            [files ...]
65
66Formatter for Python code.
67
68positional arguments:
69  files                 reads from stdin when no files are specified.
70
71optional arguments:
72  -h, --help            show this help message and exit
73  -v, --version         show program's version number and exit
74  -d, --diff            print the diff for the fixed source
75  -i, --in-place        make changes to files in place
76  -q, --quiet           output nothing and set return value
77  -r, --recursive       run recursively over directories
78  -l START-END, --lines START-END
79                        range of lines to reformat, one-based
80  -e PATTERN, --exclude PATTERN
81                        patterns for files to exclude from formatting
82  --style STYLE         specify formatting style: either a style name (for
83                        example "pep8" or "google"), or the name of a file
84                        with style settings. The default is pep8 unless a
85                        .style.yapf or setup.cfg or pyproject.toml file
86                        located in the same directory as the source or one of
87                        its parent directories (for stdin, the current
88                        directory is used).
89  --style-help          show style settings and exit; this output can be saved
90                        to .style.yapf to make your settings permanent
91  --no-local-style      don't search for local style definition
92  -p, --parallel        run YAPF in parallel when formatting multiple files.
93  -m, --print-modified  print out file names of modified files
94  -vv, --verbose        print out file names while processing
95```
96
97
98### Return Codes
99
100Normally YAPF returns zero on successful program termination and non-zero
101otherwise.
102
103If `--diff` is supplied, YAPF returns zero when no changes were necessary,
104non-zero otherwise (including program error). You can use this in a CI workflow
105to test that code has been YAPF-formatted.
106
107### Excluding files from formatting (.yapfignore or pyproject.toml)
108
109In addition to exclude patterns provided on commandline, YAPF looks for
110additional patterns specified in a file named `.yapfignore` or `pyproject.toml`
111located in the working directory from which YAPF is invoked.
112
113`.yapfignore`'s syntax is similar to UNIX's filename pattern matching:
114
115```
116*       matches everything
117?       matches any single character
118[seq]   matches any character in seq
119[!seq]  matches any character not in seq
120```
121
122Note that no entry should begin with `./`.
123
124If you use `pyproject.toml`, exclude patterns are specified by `ignore_patterns` key
125in `[tool.yapfignore]` section. For example:
126
127```ini
128[tool.yapfignore]
129ignore_patterns = [
130  "temp/**/*.py",
131  "temp2/*.py"
132]
133```
134
135
136Formatting style
137================
138
139The formatting style used by YAPF is configurable and there are many "knobs"
140that can be used to tune how YAPF does formatting. See the `style.py` module
141for the full list.
142
143To control the style, run YAPF with the `--style` argument. It accepts one of
144the predefined styles (e.g., `pep8` or `google`), a path to a configuration
145file that specifies the desired style, or a dictionary of key/value pairs.
146
147The config file is a simple listing of (case-insensitive) `key = value` pairs
148with a `[style]` heading. For example:
149
150```ini
151[style]
152based_on_style = pep8
153spaces_before_comment = 4
154split_before_logical_operator = true
155```
156
157The `based_on_style` setting determines which of the predefined styles this
158custom style is based on (think of it like subclassing). Four
159styles are predefined:
160
161- `pep8` (default)
162- `google` (based off of the [Google Python Style Guide](https://github.com/google/styleguide/blob/gh-pages/pyguide.md))
163- `yapf` (for use with Google open source projects)
164- `facebook`
165
166See `_STYLE_NAME_TO_FACTORY` in [`style.py`](https://github.com/google/yapf/blob/main/yapf/yapflib/style.py) for details.
167
168It's also possible to do the same on the command line with a dictionary. For
169example:
170
171```bash
172--style='{based_on_style: pep8, indent_width: 2}'
173```
174
175This will take the `pep8` base style and modify it to have two space
176indentations.
177
178YAPF will search for the formatting style in the following manner:
179
1801. Specified on the command line
1812. In the `[style]` section of a `.style.yapf` file in either the current
182   directory or one of its parent directories.
1833. In the `[yapf]` section of a `setup.cfg` file in either the current
184   directory or one of its parent directories.
1854. In the `[tool.yapf]` section of a `pyproject.toml` file in either the current
186   directory or one of its parent directories.
1875. In the `[style]` section of a `~/.config/yapf/style` file in your home
188   directory.
189
190If none of those files are found, the default style PEP8 is used.
191
192
193Example
194=======
195
196An example of the type of formatting that YAPF can do, it will take this ugly
197code:
198
199```python
200x = {  'a':37,'b':42,
201
202'c':927}
203
204y = 'hello ''world'
205z = 'hello '+'world'
206a = 'hello {}'.format('world')
207class foo  (     object  ):
208  def f    (self   ):
209    return       37*-+2
210  def g(self, x,y=42):
211      return y
212def f  (   a ) :
213  return      37+-+a[42-x :  y**3]
214```
215
216and reformat it into:
217
218```python
219x = {'a': 37, 'b': 42, 'c': 927}
220
221y = 'hello ' 'world'
222z = 'hello ' + 'world'
223a = 'hello {}'.format('world')
224
225
226class foo(object):
227    def f(self):
228        return 37 * -+2
229
230    def g(self, x, y=42):
231        return y
232
233
234def f(a):
235    return 37 + -+a[42 - x:y**3]
236```
237
238
239## Example as a module
240
241The two main APIs for calling YAPF are `FormatCode` and `FormatFile`, these
242share several arguments which are described below:
243
244```python
245>>> from yapf.yapflib.yapf_api import FormatCode  # reformat a string of code
246
247>>> formatted_code, changed = FormatCode("f ( a = 1, b = 2 )")
248>>> formatted_code
249'f(a=1, b=2)\n'
250>>> changed
251True
252```
253
254A `style_config` argument: Either a style name or a path to a file that
255contains formatting style settings. If None is specified, use the default style
256as set in `style.DEFAULT_STYLE_FACTORY`.
257
258```python
259>>> FormatCode("def g():\n  return True", style_config='pep8')[0]
260'def g():\n    return True\n'
261```
262
263A `lines` argument: A list of tuples of lines (ints), [start, end], that we
264want to format. The lines are 1-based indexed. It can be used by third-party
265code (e.g., IDEs) when reformatting a snippet of code rather than a whole file.
266
267```python
268>>> FormatCode("def g( ):\n    a=1\n    b = 2\n    return a==b", lines=[(1, 1), (2, 3)])[0]
269'def g():\n    a = 1\n    b = 2\n    return a==b\n'
270```
271
272A `print_diff` (bool): Instead of returning the reformatted source, return a
273diff that turns the formatted source into reformatted source.
274
275```diff
276>>> print(FormatCode("a==b", filename="foo.py", print_diff=True)[0])
277--- foo.py (original)
278+++ foo.py (reformatted)
279@@ -1 +1 @@
280-a==b
281+a == b
282```
283
284Note: the `filename` argument for `FormatCode` is what is inserted into the
285diff, the default is `<unknown>`.
286
287`FormatFile` returns reformatted code from the passed file along with its encoding:
288
289```python
290>>> from yapf.yapflib.yapf_api import FormatFile  # reformat a file
291
292>>> print(open("foo.py").read())  # contents of file
293a==b
294
295>>> reformatted_code, encoding, changed = FormatFile("foo.py")
296>>> formatted_code
297'a == b\n'
298>>> encoding
299'utf-8'
300>>> changed
301True
302```
303
304The `in_place` argument saves the reformatted code back to the file:
305
306```python
307>>> FormatFile("foo.py", in_place=True)[:2]
308(None, 'utf-8')
309
310>>> print(open("foo.py").read())  # contents of file (now fixed)
311a == b
312```
313
314
315## Formatting diffs
316
317Options:
318
319```console
320usage: yapf-diff [-h] [-i] [-p NUM] [--regex PATTERN] [--iregex PATTERN][-v]
321                 [--style STYLE] [--binary BINARY]
322
323This script reads input from a unified diff and reformats all the changed
324lines. This is useful to reformat all the lines touched by a specific patch.
325Example usage for git/svn users:
326
327  git diff -U0 --no-color --relative HEAD^ | yapf-diff -i
328  svn diff --diff-cmd=diff -x-U0 | yapf-diff -p0 -i
329
330It should be noted that the filename contained in the diff is used
331unmodified to determine the source file to update. Users calling this script
332directly should be careful to ensure that the path in the diff is correct
333relative to the current working directory.
334
335optional arguments:
336  -h, --help            show this help message and exit
337  -i, --in-place        apply edits to files instead of displaying a diff
338  -p NUM, --prefix NUM  strip the smallest prefix containing P slashes
339  --regex PATTERN       custom pattern selecting file paths to reformat
340                        (case sensitive, overrides -iregex)
341  --iregex PATTERN      custom pattern selecting file paths to reformat
342                        (case insensitive, overridden by -regex)
343  -v, --verbose         be more verbose, ineffective without -i
344  --style STYLE         specify formatting style: either a style name (for
345                        example "pep8" or "google"), or the name of a file
346                        with style settings. The default is pep8 unless a
347                        .style.yapf or setup.cfg or pyproject.toml file
348                        located in the same directory as the source or one of
349                        its parent directories (for stdin, the current
350                        directory is used).
351  --binary BINARY       location of binary to use for YAPF
352```
353
354## Python features not yet supported
355* Python 3.12 – [PEP 695 – Type Parameter Syntax](https://peps.python.org/pep-0695/) – [YAPF #1170](https://github.com/google/yapf/issues/1170)
356* Python 3.12 – [PEP 701 – Syntactic formalization of f-strings](https://peps.python.org/pep-0701/) – [YAPF #1136](https://github.com/google/yapf/issues/1136)
357
358## Knobs
359
360#### `ALIGN_CLOSING_BRACKET_WITH_VISUAL_INDENT`
361
362>    Align closing bracket with visual indentation.
363
364#### `ALLOW_MULTILINE_LAMBDAS`
365
366>    Allow lambdas to be formatted on more than one line.
367
368#### `ALLOW_MULTILINE_DICTIONARY_KEYS`
369
370>    Allow dictionary keys to exist on multiple lines. For example:
371
372```python
373    x = {
374        ('this is the first element of a tuple',
375         'this is the second element of a tuple'):
376             value,
377    }
378```
379
380#### `ALLOW_SPLIT_BEFORE_DEFAULT_OR_NAMED_ASSIGNS`
381
382>    Allow splitting before a default / named assignment in an argument list.
383
384#### `ALLOW_SPLIT_BEFORE_DICT_VALUE`
385
386>    Allow splits before the dictionary value.
387
388#### `ARITHMETIC_PRECEDENCE_INDICATION`
389
390>    Let spacing indicate operator precedence. For example:
391
392```python
393    a = 1 * 2 + 3 / 4
394    b = 1 / 2 - 3 * 4
395    c = (1 + 2) * (3 - 4)
396    d = (1 - 2) / (3 + 4)
397    e = 1 * 2 - 3
398    f = 1 + 2 + 3 + 4
399```
400
401>    will be formatted as follows to indicate precedence:
402
403```python
404    a = 1*2 + 3/4
405    b = 1/2 - 3*4
406    c = (1+2) * (3-4)
407    d = (1-2) / (3+4)
408    e = 1*2 - 3
409    f = 1 + 2 + 3 + 4
410```
411
412#### `BLANK_LINES_AROUND_TOP_LEVEL_DEFINITION`
413
414>    Sets the number of desired blank lines surrounding top-level function and
415>    class definitions. For example:
416
417```python
418    class Foo:
419        pass
420                       # <------ having two blank lines here
421                       # <------ is the default setting
422    class Bar:
423        pass
424```
425
426#### `BLANK_LINE_BEFORE_CLASS_DOCSTRING`
427
428>    Insert a blank line before a class-level docstring.
429
430#### `BLANK_LINE_BEFORE_MODULE_DOCSTRING`
431
432>    Insert a blank line before a module docstring.
433
434#### `BLANK_LINE_BEFORE_NESTED_CLASS_OR_DEF`
435
436>    Insert a blank line before a `def` or `class` immediately nested within
437>    another `def` or `class`. For example:
438
439```python
440    class Foo:
441                       # <------ this blank line
442        def method():
443            pass
444```
445
446#### `BLANK_LINES_BETWEEN_TOP_LEVEL_IMPORTS_AND_VARIABLES`
447
448>    Sets the number of desired blank lines between top-level imports and
449>    variable definitions. Useful for compatibility with tools like isort.
450
451#### `COALESCE_BRACKETS`
452
453>    Do not split consecutive brackets. Only relevant when
454>    `DEDENT_CLOSING_BRACKETS` or `INDENT_CLOSING_BRACKETS` is set. For example:
455
456```python
457    call_func_that_takes_a_dict(
458        {
459            'key1': 'value1',
460            'key2': 'value2',
461        }
462    )
463```
464
465>    would reformat to:
466
467```python
468    call_func_that_takes_a_dict({
469        'key1': 'value1',
470        'key2': 'value2',
471    })
472```
473
474#### `COLUMN_LIMIT`
475
476>    The column limit (or max line-length)
477
478#### `CONTINUATION_ALIGN_STYLE`
479
480>    The style for continuation alignment. Possible values are:
481
482>    - `SPACE`: Use spaces for continuation alignment. This is default
483>      behavior.
484>    - `FIXED`: Use fixed number (`CONTINUATION_INDENT_WIDTH`) of columns
485>      (i.e. `CONTINUATION_INDENT_WIDTH`/`INDENT_WIDTH` tabs or
486>      `CONTINUATION_INDENT_WIDTH` spaces) for continuation alignment.
487>    - `VALIGN-RIGHT`: Vertically align continuation lines to multiple of
488>      `INDENT_WIDTH` columns. Slightly right (one tab or a few spaces) if cannot
489>      vertically align continuation lines with indent characters.
490
491#### `CONTINUATION_INDENT_WIDTH`
492
493>    Indent width used for line continuations.
494
495#### `DEDENT_CLOSING_BRACKETS`
496
497>    Put closing brackets on a separate line, dedented, if the bracketed
498>    expression can't fit in a single line. Applies to all kinds of brackets,
499>    including function definitions and calls. For example:
500
501```python
502    config = {
503        'key1': 'value1',
504        'key2': 'value2',
505    }  # <--- this bracket is dedented and on a separate line
506
507    time_series = self.remote_client.query_entity_counters(
508        entity='dev3246.region1',
509        key='dns.query_latency_tcp',
510        transform=Transformation.AVERAGE(window=timedelta(seconds=60)),
511        start_ts=now()-timedelta(days=3),
512        end_ts=now(),
513    )  # <--- this bracket is dedented and on a separate line
514```
515
516#### `DISABLE_ENDING_COMMA_HEURISTIC`
517
518>    Disable the heuristic which places each list element on a separate line if
519>    the list is comma-terminated.
520>
521>    Note: The behavior of this flag changed in v0.40.3.  Before, if this flag
522>    was true, we would split lists that contained a trailing comma or a
523>    comment.  Now, we have a separate flag, `DISABLE_SPLIT_LIST_WITH_COMMENT`,
524>    that controls splitting when a list contains a comment.  To get the old
525>    behavior, set both flags to true.  More information in
526>    [CHANGELOG.md](CHANGELOG.md#new-disable_split_list_with_comment-flag).
527
528#### `DISABLE_SPLIT_LIST_WITH_COMMENT`
529
530>    Don't put every element on a new line within a list that contains
531>    interstitial comments.
532>
533>    Without this flag (default):
534>
535>    ```
536>    [
537>      a,
538>      b,  #
539>      c
540>    ]
541>    ```
542>
543>    With this flag:
544>
545>    ```
546>    [
547>      a, b,  #
548>      c
549>    ]
550>    ```
551>
552>    This mirrors the behavior of clang-format and is useful for forming
553>    "logical groups" of elements in a list.  It also works in function
554>    declarations.
555
556#### `EACH_DICT_ENTRY_ON_SEPARATE_LINE`
557
558>    Place each dictionary entry onto its own line.
559
560#### `FORCE_MULTILINE_DICT`
561
562>    Respect `EACH_DICT_ENTRY_ON_SEPARATE_LINE` even if the line is shorter than
563>    `COLUMN_LIMIT`.
564
565#### `I18N_COMMENT`
566
567>    The regex for an internationalization comment. The presence of this comment
568>    stops reformatting of that line, because the comments are required to be
569>    next to the string they translate.
570
571#### `I18N_FUNCTION_CALL`
572
573>    The internationalization function call names. The presence of this function
574>    stops reformatting on that line, because the string it has cannot be moved
575>    away from the i18n comment.
576
577#### `INDENT_BLANK_LINES`
578
579>    Set to `True` to prefer indented blank lines rather than empty
580
581#### `INDENT_CLOSING_BRACKETS`
582
583>    Put closing brackets on a separate line, indented, if the bracketed
584>    expression can't fit in a single line. Applies to all kinds of brackets,
585>    including function definitions and calls. For example:
586
587```python
588    config = {
589        'key1': 'value1',
590        'key2': 'value2',
591        }  # <--- this bracket is indented and on a separate line
592
593    time_series = self.remote_client.query_entity_counters(
594        entity='dev3246.region1',
595        key='dns.query_latency_tcp',
596        transform=Transformation.AVERAGE(window=timedelta(seconds=60)),
597        start_ts=now()-timedelta(days=3),
598        end_ts=now(),
599        )  # <--- this bracket is indented and on a separate line
600```
601
602#### `INDENT_DICTIONARY_VALUE`
603
604>    Indent the dictionary value if it cannot fit on the same line as the
605>    dictionary key. For example:
606
607```python
608    config = {
609        'key1':
610            'value1',
611        'key2': value1 +
612                value2,
613    }
614```
615
616#### `INDENT_WIDTH`
617
618>    The number of columns to use for indentation.
619
620#### `JOIN_MULTIPLE_LINES`
621
622>    Join short lines into one line. E.g., single line `if` statements.
623
624#### `NO_SPACES_AROUND_SELECTED_BINARY_OPERATORS`
625
626>    Do not include spaces around selected binary operators. For example:
627
628```python
629    1 + 2 * 3 - 4 / 5
630```
631
632>    will be formatted as follows when configured with `*`, `/`:
633
634```python
635    1 + 2*3 - 4/5
636```
637
638#### `SPACE_BETWEEN_ENDING_COMMA_AND_CLOSING_BRACKET`
639
640>    Insert a space between the ending comma and closing bracket of a list, etc.
641
642#### `SPACE_INSIDE_BRACKETS`
643
644    Use spaces inside brackets, braces, and parentheses.  For example:
645
646```python
647        method_call( 1 )
648        my_dict[ 3 ][ 1 ][ get_index( *args, **kwargs ) ]
649        my_set = { 1, 2, 3 }
650```
651
652#### `SPACES_AROUND_DEFAULT_OR_NAMED_ASSIGN`
653
654>    Set to `True` to prefer spaces around the assignment operator for default
655>    or keyword arguments.
656
657#### `SPACES_AROUND_DICT_DELIMITERS`
658
659>    Adds a space after the opening '{' and before the ending '}' dict delimiters.
660
661```python
662        {1: 2}
663```
664
665>    will be formatted as:
666
667```python
668        { 1: 2 }
669```
670
671#### `SPACES_AROUND_LIST_DELIMITERS`
672
673>    Adds a space after the opening '[' and before the ending ']' list delimiters.
674
675```python
676    [1, 2]
677```
678
679>    will be formatted as:
680
681```python
682    [ 1, 2 ]
683```
684
685#### `SPACES_AROUND_POWER_OPERATOR`
686
687>    Set to `True` to prefer using spaces around `**`.
688
689#### `SPACES_AROUND_SUBSCRIPT_COLON`
690
691>    Use spaces around the subscript / slice operator.  For example:
692
693```python
694    my_list[1 : 10 : 2]
695```
696
697##### `SPACES_AROUND_TUPLE_DELIMITERS`
698
699>    Adds a space after the opening '(' and before the ending ')' tuple delimiters.
700
701```python
702    (1, 2, 3)
703```
704
705>    will be formatted as:
706
707```python
708    ( 1, 2, 3 )
709```
710
711#### `SPACES_BEFORE_COMMENT`
712
713>    The number of spaces required before a trailing comment.
714>    This can be a single value (representing the number of spaces
715>    before each trailing comment) or list of values (representing
716>    alignment column values; trailing comments within a block will
717>    be aligned to the first column value that is greater than the maximum
718>    line length within the block).
719
720> **Note:** Lists of values may need to be quoted in some contexts
721> (eg. shells or editor config files).
722
723>    For example, with `spaces_before_comment=5`:
724
725```python
726    1 + 1 # Adding values
727```
728
729>    will be formatted as:
730
731```python
732    1 + 1     # Adding values <-- 5 spaces between the end of the statement and comment
733```
734
735>    with `spaces_before_comment="15, 20"`:
736
737```python
738    1 + 1 # Adding values
739    two + two # More adding
740
741    longer_statement # This is a longer statement
742    short # This is a shorter statement
743
744    a_very_long_statement_that_extends_beyond_the_final_column # Comment
745    short # This is a shorter statement
746```
747
748>    will be formatted as:
749
750```python
751    1 + 1          # Adding values <-- end of line comments in block aligned to col 15
752    two + two      # More adding
753
754    longer_statement    # This is a longer statement <-- end of line comments in block aligned to col 20
755    short               # This is a shorter statement
756
757    a_very_long_statement_that_extends_beyond_the_final_column  # Comment <-- the end of line comments are aligned based on the line length
758    short                                                       # This is a shorter statement
759```
760
761#### `SPLIT_ALL_COMMA_SEPARATED_VALUES`
762
763>    If a comma separated list (`dict`, `list`, `tuple`, or function `def`) is
764>    on a line that is too long, split such that each element is on a separate
765>    line.
766
767#### `SPLIT_ALL_TOP_LEVEL_COMMA_SEPARATED_VALUES`
768
769>    Variation on `SPLIT_ALL_COMMA_SEPARATED_VALUES` in which, if a
770>    subexpression with a comma fits in its starting line, then the
771>    subexpression is not split. This avoids splits like the one for
772>    `b` in this code:
773
774```python
775    abcdef(
776        aReallyLongThing: int,
777        b: [Int,
778            Int])
779```
780
781>    with the new knob this is split as:
782
783```python
784    abcdef(
785        aReallyLongThing: int,
786        b: [Int, Int])
787```
788
789#### `SPLIT_ARGUMENTS_WHEN_COMMA_TERMINATED`
790
791>    Split before arguments if the argument list is terminated by a comma.
792
793#### `SPLIT_BEFORE_ARITHMETIC_OPERATOR`
794
795>    Set to `True` to prefer splitting before `+`, `-`, `*`, `/`, `//`, or `@`
796>    rather than after.
797
798#### `SPLIT_BEFORE_BITWISE_OPERATOR`
799
800>    Set to `True` to prefer splitting before `&`, `|` or `^` rather than after.
801
802#### `SPLIT_BEFORE_CLOSING_BRACKET`
803
804>    Split before the closing bracket if a `list` or `dict` literal doesn't fit
805>    on a single line.
806
807#### `SPLIT_BEFORE_DICT_SET_GENERATOR`
808
809>    Split before a dictionary or set generator (`comp_for`). For example, note
810>    the split before the `for`:
811
812```python
813    foo = {
814        variable: 'Hello world, have a nice day!'
815        for variable in bar if variable != 42
816    }
817```
818
819#### `SPLIT_BEFORE_DOT`
820
821>    Split before the `.` if we need to split a longer expression:
822
823```python
824    foo = ('This is a really long string: {}, {}, {}, {}'.format(a, b, c, d))
825```
826
827>    would reformat to something like:
828
829```python
830    foo = ('This is a really long string: {}, {}, {}, {}'
831           .format(a, b, c, d))
832```
833
834#### `SPLIT_BEFORE_EXPRESSION_AFTER_OPENING_PAREN`
835
836>    Split after the opening paren which surrounds an expression if it doesn't
837>    fit on a single line.
838
839#### `SPLIT_BEFORE_FIRST_ARGUMENT`
840
841>    If an argument / parameter list is going to be split, then split before the
842>    first argument.
843
844#### `SPLIT_BEFORE_LOGICAL_OPERATOR`
845
846>    Set to `True` to prefer splitting before `and` or `or` rather than after.
847
848#### `SPLIT_BEFORE_NAMED_ASSIGNS`
849
850>    Split named assignments onto individual lines.
851
852#### `SPLIT_COMPLEX_COMPREHENSION`
853
854>    For list comprehensions and generator expressions with multiple clauses
855>    (e.g multiple `for` calls, `if` filter expressions) and which need to be
856>    reflowed, split each clause onto its own line. For example:
857
858```python
859    result = [
860        a_var + b_var for a_var in xrange(1000) for b_var in xrange(1000)
861        if a_var % b_var]
862```
863
864>    would reformat to something like:
865
866```python
867    result = [
868        a_var + b_var
869        for a_var in xrange(1000)
870        for b_var in xrange(1000)
871        if a_var % b_var]
872```
873
874#### `SPLIT_PENALTY_AFTER_OPENING_BRACKET`
875
876>    The penalty for splitting right after the opening bracket.
877
878#### `SPLIT_PENALTY_AFTER_UNARY_OPERATOR`
879
880>    The penalty for splitting the line after a unary operator.
881
882#### `SPLIT_PENALTY_ARITHMETIC_OPERATOR`
883
884>    The penalty of splitting the line around the `+`, `-`, `*`, `/`, `//`, `%`,
885>    and `@` operators.
886
887#### `SPLIT_PENALTY_BEFORE_IF_EXPR`
888
889>    The penalty for splitting right before an `if` expression.
890
891#### `SPLIT_PENALTY_BITWISE_OPERATOR`
892
893>    The penalty of splitting the line around the `&`, `|`, and `^` operators.
894
895#### `SPLIT_PENALTY_COMPREHENSION`
896
897>    The penalty for splitting a list comprehension or generator expression.
898
899#### `SPLIT_PENALTY_EXCESS_CHARACTER`
900
901>    The penalty for characters over the column limit.
902
903#### `SPLIT_PENALTY_FOR_ADDED_LINE_SPLIT`
904
905>    The penalty incurred by adding a line split to the logical line. The more
906>    line splits added the higher the penalty.
907
908#### `SPLIT_PENALTY_IMPORT_NAMES`
909
910>    The penalty of splitting a list of `import as` names. For example:
911
912```python
913    from a_very_long_or_indented_module_name_yada_yad import (long_argument_1,
914                                                              long_argument_2,
915                                                              long_argument_3)
916```
917
918>    would reformat to something like:
919
920```python
921    from a_very_long_or_indented_module_name_yada_yad import (
922        long_argument_1, long_argument_2, long_argument_3)
923```
924
925#### `SPLIT_PENALTY_LOGICAL_OPERATOR`
926
927>    The penalty of splitting the line around the `and` and `or` operators.
928
929#### `USE_TABS`
930
931>    Use the Tab character for indentation.
932
933
934## (Potentially) Frequently Asked Questions
935
936### Why does YAPF destroy my awesome formatting?
937
938YAPF tries very hard to get the formatting correct. But for some code, it won't
939be as good as hand-formatting. In particular, large data literals may become
940horribly disfigured under YAPF.
941
942The reasons for this are manyfold. In short, YAPF is simply a tool to help
943with development. It will format things to coincide with the style guide, but
944that may not equate with readability.
945
946What can be done to alleviate this situation is to indicate regions YAPF should
947ignore when reformatting something:
948
949```python
950# yapf: disable
951FOO = {
952    # ... some very large, complex data literal.
953}
954
955BAR = [
956    # ... another large data literal.
957]
958# yapf: enable
959```
960
961You can also disable formatting for a single literal like this:
962
963```python
964BAZ = {
965    (1, 2, 3, 4),
966    (5, 6, 7, 8),
967    (9, 10, 11, 12),
968}  # yapf: disable
969```
970
971To preserve the nice dedented closing brackets, use the
972`dedent_closing_brackets` in your style. Note that in this case all
973brackets, including function definitions and calls, are going to use
974that style.  This provides consistency across the formatted codebase.
975
976### Why Not Improve Existing Tools?
977
978We wanted to use clang-format's reformatting algorithm. It's very powerful and
979designed to come up with the best formatting possible. Existing tools were
980created with different goals in mind, and would require extensive modifications
981to convert to using clang-format's algorithm.
982
983### Can I Use YAPF In My Program?
984
985Please do! YAPF was designed to be used as a library as well as a command line
986tool. This means that a tool or IDE plugin is free to use YAPF.
987
988### I still get non-PEP8 compliant code! Why?
989
990YAPF tries very hard to be fully PEP 8 compliant. However, it is paramount
991to not risk altering the semantics of your code. Thus, YAPF tries to be as
992safe as possible and does not change the token stream
993(e.g., by adding parentheses).
994All these cases however, can be easily fixed manually. For instance,
995
996```python
997from my_package import my_function_1, my_function_2, my_function_3, my_function_4, my_function_5
998
999FOO = my_variable_1 + my_variable_2 + my_variable_3 + my_variable_4 + my_variable_5 + my_variable_6 + my_variable_7 + my_variable_8
1000```
1001
1002won't be split, but you can easily get it right by just adding parentheses:
1003
1004```python
1005from my_package import (my_function_1, my_function_2, my_function_3,
1006                        my_function_4, my_function_5)
1007
1008FOO = (my_variable_1 + my_variable_2 + my_variable_3 + my_variable_4 +
1009       my_variable_5 + my_variable_6 + my_variable_7 + my_variable_8)
1010```
1011
1012
1013## Gory Details
1014
1015### Algorithm Design
1016
1017The main data structure in YAPF is the `LogicalLine` object. It holds a list
1018of `FormatToken`\s, that we would want to place on a single line if there
1019were no column limit. An exception being a comment in the middle of an
1020expression statement will force the line to be formatted on more than one line.
1021The formatter works on one `LogicalLine` object at a time.
1022
1023An `LogicalLine` typically won't affect the formatting of lines before or
1024after it. There is a part of the algorithm that may join two or more
1025`LogicalLine`\s into one line. For instance, an if-then statement with a
1026short body can be placed on a single line:
1027
1028```python
1029if a == 42: continue
1030```
1031
1032YAPF's formatting algorithm creates a weighted tree that acts as the solution
1033space for the algorithm. Each node in the tree represents the result of a
1034formatting decision --- i.e., whether to split or not to split before a token.
1035Each formatting decision has a cost associated with it. Therefore, the cost is
1036realized on the edge between two nodes. (In reality, the weighted tree doesn't
1037have separate edge objects, so the cost resides on the nodes themselves.)
1038
1039For example, take the following Python code snippet. For the sake of this
1040example, assume that line (1) violates the column limit restriction and needs to
1041be reformatted.
1042
1043```python
1044def xxxxxxxxxxx(aaaaaaaaaaaa, bbbbbbbbb, cccccccc, dddddddd, eeeeee):  # 1
1045    pass                                                               # 2
1046```
1047
1048For line (1), the algorithm will build a tree where each node (a
1049`FormattingDecisionState` object) is the state of the line at that token given
1050the decision to split before the token or not. Note: the `FormatDecisionState`
1051objects are copied by value so each node in the graph is unique and a change in
1052one doesn't affect other nodes.
1053
1054Heuristics are used to determine the costs of splitting or not splitting.
1055Because a node holds the state of the tree up to a token's insertion, it can
1056easily determine if a splitting decision will violate one of the style
1057requirements. For instance, the heuristic is able to apply an extra penalty to
1058the edge when not splitting between the previous token and the one being added.
1059
1060There are some instances where we will never want to split the line, because
1061doing so will always be detrimental (i.e., it will require a backslash-newline,
1062which is very rarely desirable). For line (1), we will never want to split the
1063first three tokens: `def`, `xxxxxxxxxxx`, and `(`. Nor will we want to
1064split between the `)` and the `:` at the end. These regions are said to be
1065"unbreakable." This is reflected in the tree by there not being a "split"
1066decision (left hand branch) within the unbreakable region.
1067
1068Now that we have the tree, we determine what the "best" formatting is by finding
1069the path through the tree with the lowest cost.
1070
1071And that's it!
1072