blob: 21d06920ec1c05dae1b4fee53b76566a896384fe [file] [log] [blame]
Bill Wendling7d623452015-03-18 13:36:07 -07001====
2YAPF
3====
4
Bill Wendling19c44d02015-04-07 23:48:05 -07005.. image:: https://badge.fury.io/py/yapf.svg
Ronald Eddy Jr808d7d22017-12-25 22:38:41 -08006 :target: https://badge.fury.io/py/yapf
Bill Wendling19c44d02015-04-07 23:48:05 -07007 :alt: PyPI version
8
Bill Wendlingfb8ab382015-03-18 20:24:14 -07009.. image:: https://travis-ci.org/google/yapf.svg?branch=master
10 :target: https://travis-ci.org/google/yapf
11 :alt: Build status
12
Bill Wendling14ac8812015-04-05 02:47:32 -070013.. image:: https://coveralls.io/repos/google/yapf/badge.svg?branch=master
14 :target: https://coveralls.io/r/google/yapf?branch=master
15 :alt: Coverage status
16
Bill Wendlingf09121c2015-10-20 22:59:33 -070017
Bill Wendling7d623452015-03-18 13:36:07 -070018Introduction
19============
20
Bill Wendling5632e672015-03-29 17:06:07 -070021Most of the current formatters for Python --- e.g., autopep8, and pep8ify ---
22are made to remove lint errors from code. This has some obvious limitations.
23For instance, code that conforms to the PEP 8 guidelines may not be
24reformatted. But it doesn't mean that the code looks good.
Bill Wendling7d623452015-03-18 13:36:07 -070025
26YAPF takes a different approach. It's based off of 'clang-format', developed by
27Daniel Jasper. In essence, the algorithm takes the code and reformats it to the
28best formatting that conforms to the style guide, even if the original code
Peter Bengtsson1c60ad72015-03-24 20:05:39 -070029didn't violate the style guide. The idea is also similar to the 'gofmt' tool for
Eli Bendersky07072f82015-03-23 06:41:14 -070030the Go programming language: end all holy wars about formatting - if the whole
Samuel Dion-Girardeau5ae63492016-09-08 21:01:20 -040031codebase of a project is simply piped through YAPF whenever modifications are
Eli Bendersky07072f82015-03-23 06:41:14 -070032made, the style remains consistent throughout the project and there's no point
33arguing about style in every code review.
Bill Wendling7d623452015-03-18 13:36:07 -070034
35The ultimate goal is that the code YAPF produces is as good as the code that a
Bill Wendling8fb9c482015-03-29 17:32:07 -070036programmer would write if they were following the style guide. It takes away
37some of the drudgery of maintaining your code.
Bill Wendling7d623452015-03-18 13:36:07 -070038
José Padilla45aea8e2018-01-16 12:26:33 -050039Try out YAPF with this `online demo <https://yapf.now.sh>`_.
José Padilla2774c1b2017-12-19 16:59:52 -050040
Bill Wendlingf5e50b62015-03-28 23:38:12 -070041.. footer::
Bill Wendling52e04112015-03-18 20:42:26 -070042
43 YAPF is not an official Google product (experimental or otherwise), it is
44 just code that happens to be owned by Google.
45
Bill Wendling7d623452015-03-18 13:36:07 -070046.. contents::
47
Bill Wendlingf09121c2015-10-20 22:59:33 -070048
Bill Wendling7d623452015-03-18 13:36:07 -070049Installation
50============
51
Bill Wendling6e8ca7b2015-10-25 01:16:43 -070052To install YAPF from PyPI:
53
Bill Wendling4f96aab2016-07-16 15:52:51 -070054.. code-block::
Eli Bendersky8a365362015-03-25 18:42:22 -070055
Eli Benderskye0e83c12015-04-06 20:23:30 -070056 $ pip install yapf
57
Diogo de Campos2f246c02016-10-06 14:04:38 +020058(optional) If you are using Python 2.7 and want to enable multiprocessing:
59
60.. code-block::
61
62 $ pip install futures
63
Eli Benderskye0e83c12015-04-06 20:23:30 -070064YAPF is still considered in "alpha" stage, and the released version may change
65often; therefore, the best way to keep up-to-date with the latest development
66is to clone this repository.
67
68Note that if you intend to use YAPF as a command-line tool rather than as a
69library, installation is not necessary. YAPF supports being run as a directory
70by the Python interpreter. If you cloned/unzipped YAPF into ``DIR``, it's
Bill Wendling6e8ca7b2015-10-25 01:16:43 -070071possible to run:
72
Bill Wendling4f96aab2016-07-16 15:52:51 -070073.. code-block::
Eli Bendersky07072f82015-03-23 06:41:14 -070074
Eli Benderskyb3678b32015-03-25 14:16:11 -070075 $ PYTHONPATH=DIR python DIR/yapf [options] ...
Eli Bendersky07072f82015-03-23 06:41:14 -070076
Bill Wendlingf09121c2015-10-20 22:59:33 -070077
Eli Bendersky5eb88232015-03-27 06:27:11 -070078Python versions
79===============
80
Bill Wendlingfe6460f2018-01-26 15:08:07 -080081YAPF supports Python 2.7 and 3.6.4+. (Note that some Python 3 features may fail
82to parse with Python versions before 3.6.4.)
Eli Bendersky5eb88232015-03-27 06:27:11 -070083
84YAPF requires the code it formats to be valid Python for the version YAPF itself
85runs under. Therefore, if you format Python 3 code with YAPF, run YAPF itself
86under Python 3 (and similarly for Python 2).
87
Bill Wendlingf09121c2015-10-20 22:59:33 -070088
Bill Wendling7d623452015-03-18 13:36:07 -070089Usage
90=====
91
Bill Wendlingfa22c892015-03-18 13:42:25 -070092Options::
Bill Wendling7d623452015-03-18 13:36:07 -070093
Bill Wendlingf09121c2015-10-20 22:59:33 -070094 usage: yapf [-h] [-v] [-d | -i] [-r | -l START-END] [-e PATTERN]
Diogo de Campos2f246c02016-10-06 14:04:38 +020095 [--style STYLE] [--style-help] [--no-local-style] [-p]
Bill Wendling7bfc0a92017-10-16 03:22:19 -070096 [-vv]
Bill Wendlingf09121c2015-10-20 22:59:33 -070097 [files [files ...]]
Bill Wendling7d623452015-03-18 13:36:07 -070098
Bill Wendlingfa22c892015-03-18 13:42:25 -070099 Formatter for Python code.
Bill Wendling7d623452015-03-18 13:36:07 -0700100
Bill Wendlingfa22c892015-03-18 13:42:25 -0700101 positional arguments:
102 files
103
104 optional arguments:
105 -h, --help show this help message and exit
Bill Wendlingf09121c2015-10-20 22:59:33 -0700106 -v, --version show version number and exit
107 -d, --diff print the diff for the fixed source
108 -i, --in-place make changes to files in place
109 -r, --recursive run recursively over directories
110 -l START-END, --lines START-END
111 range of lines to reformat, one-based
112 -e PATTERN, --exclude PATTERN
113 patterns for files to exclude from formatting
Eli Bendersky83d2bd02015-03-23 06:33:48 -0700114 --style STYLE specify formatting style: either a style name (for
115 example "pep8" or "google"), or the name of a file
Sam Clegg5170c3a2015-04-16 12:18:58 -0700116 with style settings. The default is pep8 unless a
Peter Ludemann827260c2017-12-20 19:54:27 -0800117 .style.yapf or setup.cfg file located in the same
118 directory as the source or one of its parent
119 directories (for stdin, the current directory is
120 used).
Bill Wendling7bfc0a92017-10-16 03:22:19 -0700121 --style-help show style settings and exit; this output can be saved
122 to .style.yapf to make your settings permanent
123 --no-local-style don't search for local style definition
Diogo de Campos2f246c02016-10-06 14:04:38 +0200124 -p, --parallel Run yapf in parallel when formatting multiple files.
125 Requires concurrent.futures in Python 2.X
Bill Wendling7bfc0a92017-10-16 03:22:19 -0700126 -vv, --verbose Print out file names while processing
Bill Wendlingf09121c2015-10-20 22:59:33 -0700127
Bill Wendling7d623452015-03-18 13:36:07 -0700128
Eli Bendersky83d2bd02015-03-23 06:33:48 -0700129Formatting style
Bill Wendlingf5e50b62015-03-28 23:38:12 -0700130================
Eli Bendersky83d2bd02015-03-23 06:33:48 -0700131
132The formatting style used by YAPF is configurable and there are many "knobs"
133that can be used to tune how YAPF does formatting. See the ``style.py`` module
134for the full list.
135
Bill Wendlingc0167792015-04-02 01:58:39 -0700136To control the style, run YAPF with the ``--style`` argument. It accepts one of
137the predefined styles (e.g., ``pep8`` or ``google``), a path to a configuration
138file that specifies the desired style, or a dictionary of key/value pairs.
139
140The config file is a simple listing of (case-insensitive) ``key = value`` pairs
Bill Wendling6e8ca7b2015-10-25 01:16:43 -0700141with a ``[style]`` heading. For example:
142
Bill Wendling4f96aab2016-07-16 15:52:51 -0700143.. code-block::
Eli Bendersky83d2bd02015-03-23 06:33:48 -0700144
145 [style]
146 based_on_style = pep8
147 spaces_before_comment = 4
148 split_before_logical_operator = true
149
150The ``based_on_style`` setting determines which of the predefined styles this
151custom style is based on (think of it like subclassing).
Bill Wendling7d623452015-03-18 13:36:07 -0700152
Bill Wendlingc0167792015-04-02 01:58:39 -0700153It's also possible to do the same on the command line with a dictionary. For
Bill Wendling6e8ca7b2015-10-25 01:16:43 -0700154example:
155
Bill Wendling4f96aab2016-07-16 15:52:51 -0700156.. code-block::
Bill Wendlingc0167792015-04-02 01:58:39 -0700157
Bill Wendlingf09121c2015-10-20 22:59:33 -0700158 --style='{based_on_style: chromium, indent_width: 4}'
Bill Wendlingc0167792015-04-02 01:58:39 -0700159
Bill Wendlingf09121c2015-10-20 22:59:33 -0700160This will take the ``chromium`` base style and modify it to have four space
Bill Wendlingc0167792015-04-02 01:58:39 -0700161indentations.
162
Bill Wendling169790e2015-10-25 03:13:13 -0700163YAPF will search for the formatting style in the following manner:
164
1651. Specified on the command line
Joshua Moravecd8d15af2015-11-05 13:16:46 -06001662. In the `[style]` section of a `.style.yapf` file in either the current
Bill Wendling169790e2015-10-25 03:13:13 -0700167 directory or one of its parent directories.
Bill Wendling821a36f2016-07-13 23:02:16 -07001683. In the `[yapf]` section of a `setup.cfg` file in either the current
Bill Wendling169790e2015-10-25 03:13:13 -0700169 directory or one of its parent directories.
1704. In the `~/.config/yapf/style` file in your home directory.
171
172If none of those files are found, the default style is used (PEP8).
173
Bill Wendlingf09121c2015-10-20 22:59:33 -0700174
Bill Wendlingf5e50b62015-03-28 23:38:12 -0700175Example
176=======
177
Sam Clegg4357fa32015-04-08 12:21:46 -0700178An example of the type of formatting that YAPF can do, it will take this ugly
179code:
Bill Wendlingf5e50b62015-03-28 23:38:12 -0700180
181.. code-block:: python
182
183 x = { 'a':37,'b':42,
184
185 'c':927}
186
187 y = 'hello ''world'
188 z = 'hello '+'world'
189 a = 'hello {}'.format('world')
190 class foo ( object ):
191 def f (self ):
192 return 37*-+2
193 def g(self, x,y=42):
194 return y
195 def f ( a ) :
196 return 37+-+a[42-x : y**3]
197
Bill Wendling8fb9c482015-03-29 17:32:07 -0700198and reformat it into:
Bill Wendlingf5e50b62015-03-28 23:38:12 -0700199
200.. code-block:: python
201
202 x = {'a': 37, 'b': 42, 'c': 927}
203
204 y = 'hello ' 'world'
205 z = 'hello ' + 'world'
206 a = 'hello {}'.format('world')
207
208
209 class foo(object):
Bill Wendling5632e672015-03-29 17:06:07 -0700210 def f(self):
211 return 37 * -+2
Bill Wendlingf5e50b62015-03-28 23:38:12 -0700212
Bill Wendling5632e672015-03-29 17:06:07 -0700213 def g(self, x, y=42):
214 return y
Bill Wendlingf5e50b62015-03-28 23:38:12 -0700215
216
217 def f(a):
Bill Wendling8d8f5122015-10-16 11:46:23 -0700218 return 37 + -+a[42 - x:y**3]
Bill Wendlingf5e50b62015-03-28 23:38:12 -0700219
Bill Wendlingf09121c2015-10-20 22:59:33 -0700220
Andy Haydena00a6bf2015-06-15 18:47:41 -0700221Example as a module
222===================
223
Andy Hayden4af71682015-06-17 15:42:43 -0700224The two main APIs for calling yapf are ``FormatCode`` and ``FormatFile``, these
225share several arguments which are described below:
Andy Haydena00a6bf2015-06-15 18:47:41 -0700226
227.. code-block:: python
228
srinivasanramarajucfa7ead2017-02-14 00:06:58 -0800229 >>> from yapf.yapflib.yapf_api import FormatCode # reformat a string of code
Łukasz Langa94089872015-09-22 16:02:26 -0700230
Andy Haydena00a6bf2015-06-15 18:47:41 -0700231 >>> FormatCode("f ( a = 1, b = 2 )")
232 'f(a=1, b=2)\n'
233
Andy Hayden4af71682015-06-17 15:42:43 -0700234A ``style_config`` argument: Either a style name or a path to a file that contains
Andy Haydena00a6bf2015-06-15 18:47:41 -0700235formatting style settings. If None is specified, use the default style
236as set in ``style.DEFAULT_STYLE_FACTORY``.
237
238.. code-block:: python
239
240 >>> FormatCode("def g():\n return True", style_config='pep8')
241 'def g():\n return True\n'
242
Andy Haydena00a6bf2015-06-15 18:47:41 -0700243A ``lines`` argument: A list of tuples of lines (ints), [start, end],
244that we want to format. The lines are 1-based indexed. It can be used by
245third-party code (e.g., IDEs) when reformatting a snippet of code rather
246than a whole file.
247
248.. code-block:: python
249
250 >>> FormatCode("def g( ):\n a=1\n b = 2\n return a==b", lines=[(1, 1), (2, 3)])
251 'def g():\n a = 1\n b = 2\n return a==b\n'
252
253A ``print_diff`` (bool): Instead of returning the reformatted source, return a
254diff that turns the formatted source into reformatter source.
255
256.. code-block:: python
257
258 >>> print(FormatCode("a==b", filename="foo.py", print_diff=True))
Bill Wendlingb8645ea2015-06-30 22:27:56 -0700259 --- foo.py (original)
260 +++ foo.py (reformatted)
Andy Haydena00a6bf2015-06-15 18:47:41 -0700261 @@ -1 +1 @@
262 -a==b
263 +a == b
264
Andy Hayden4af71682015-06-17 15:42:43 -0700265Note: the ``filename`` argument for ``FormatCode`` is what is inserted into
266the diff, the default is ``<unknown>``.
Andy Haydena00a6bf2015-06-15 18:47:41 -0700267
268``FormatFile`` returns reformatted code from the passed file along with its encoding:
269
270.. code-block:: python
271
srinivasanramarajucfa7ead2017-02-14 00:06:58 -0800272 >>> from yapf.yapflib.yapf_api import FormatFile # reformat a file
Andy Hayden4af71682015-06-17 15:42:43 -0700273
Andy Haydena00a6bf2015-06-15 18:47:41 -0700274 >>> print(open("foo.py").read()) # contents of file
275 a==b
276
277 >>> FormatFile("foo.py")
Andy Hayden4af71682015-06-17 15:42:43 -0700278 ('a == b\n', 'utf-8')
279
Bill Wendlingcfbb1242015-09-20 12:08:18 -0700280The ``in-place`` argument saves the reformatted code back to the file:
Andy Hayden4af71682015-06-17 15:42:43 -0700281
282.. code-block:: python
283
284 >>> FormatFile("foo.py", in_place=True)
285 (None, 'utf-8')
286
287 >>> print(open("foo.py").read()) # contents of file (now fixed)
288 a == b
289
Andy Haydena00a6bf2015-06-15 18:47:41 -0700290
Bill Wendlingf09121c2015-10-20 22:59:33 -0700291Knobs
292=====
293
294``ALIGN_CLOSING_BRACKET_WITH_VISUAL_INDENT``
295 Align closing bracket with visual indentation.
296
Bill Wendling996c3ee2016-05-25 23:52:24 -0700297``ALLOW_MULTILINE_LAMBDAS``
298 Allow lambdas to be formatted on more than one line.
299
Bill Wendling8d321362017-02-05 18:29:26 -0800300``ALLOW_MULTILINE_DICTIONARY_KEYS``
301 Allow dictionary keys to exist on multiple lines. For example:
302
303 .. code-block:: python
304
305 x = {
306 ('this is the first element of a tuple',
307 'this is the second element of a tuple'):
308 value,
309 }
310
Bill Wendling8a3b71f2017-08-26 02:34:03 -0700311``ALLOW_SPLIT_BEFORE_DICT_VALUE``
312 Allow splits before the dictionary value.
313
Bill Wendlingf09121c2015-10-20 22:59:33 -0700314``BLANK_LINE_BEFORE_NESTED_CLASS_OR_DEF``
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700315 Insert a blank line before a ``def`` or ``class`` immediately nested within
Bill Wendling996c3ee2016-05-25 23:52:24 -0700316 another ``def`` or ``class``. For example:
Bill Wendlingf09121c2015-10-20 22:59:33 -0700317
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700318 .. code-block:: python
Bill Wendlingf09121c2015-10-20 22:59:33 -0700319
320 class Foo:
321 # <------ this blank line
322 def method():
323 pass
324
Bill Wendling9f497522017-02-04 04:39:47 -0800325``BLANK_LINE_BEFORE_CLASS_DOCSTRING``
326 Insert a blank line before a class-level docstring.
327
Ben Plotnick7e088292016-06-09 18:29:56 -0700328``COALESCE_BRACKETS``
329 Do not split consecutive brackets. Only relevant when
330 ``DEDENT_CLOSING_BRACKETS`` is set. For example:
331
332 .. code-block:: python
333
334 call_func_that_takes_a_dict(
335 {
336 'key1': 'value1',
337 'key2': 'value2',
338 }
339 )
340
341 would reformat to:
342
343 .. code-block:: python
344
345 call_func_that_takes_a_dict({
346 'key1': 'value1',
347 'key2': 'value2',
348 })
349
350
Bill Wendlingf09121c2015-10-20 22:59:33 -0700351``COLUMN_LIMIT``
James Broadheadf4dd8042016-01-07 14:40:19 +0000352 The column limit (or max line-length)
Bill Wendlingf09121c2015-10-20 22:59:33 -0700353
354``CONTINUATION_INDENT_WIDTH``
355 Indent width used for line continuations.
356
357``DEDENT_CLOSING_BRACKETS``
358 Put closing brackets on a separate line, dedented, if the bracketed
359 expression can't fit in a single line. Applies to all kinds of brackets,
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700360 including function definitions and calls. For example:
Bill Wendlingf09121c2015-10-20 22:59:33 -0700361
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700362 .. code-block:: python
Bill Wendlingf09121c2015-10-20 22:59:33 -0700363
364 config = {
365 'key1': 'value1',
366 'key2': 'value2',
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700367 } # <--- this bracket is dedented and on a separate line
Bill Wendlingf09121c2015-10-20 22:59:33 -0700368
369 time_series = self.remote_client.query_entity_counters(
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700370 entity='dev3246.region1',
371 key='dns.query_latency_tcp',
372 transform=Transformation.AVERAGE(window=timedelta(seconds=60)),
373 start_ts=now()-timedelta(days=3),
374 end_ts=now(),
375 ) # <--- this bracket is dedented and on a separate line
Bill Wendlingf09121c2015-10-20 22:59:33 -0700376
Bill Wendling0e9b3212017-01-31 14:41:00 -0800377``EACH_DICT_ENTRY_ON_SEPARATE_LINE``
378 Place each dictionary entry onto its own line.
379
Bill Wendlingf09121c2015-10-20 22:59:33 -0700380``I18N_COMMENT``
381 The regex for an internationalization comment. The presence of this comment
382 stops reformatting of that line, because the comments are required to be
383 next to the string they translate.
384
385``I18N_FUNCTION_CALL``
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700386 The internationalization function call names. The presence of this function
Samuel Dion-Girardeau5ae63492016-09-08 21:01:20 -0400387 stops reformatting on that line, because the string it has cannot be moved
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700388 away from the i18n comment.
Bill Wendlingf09121c2015-10-20 22:59:33 -0700389
390``INDENT_DICTIONARY_VALUE``
391 Indent the dictionary value if it cannot fit on the same line as the
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700392 dictionary key. For example:
Bill Wendlingf09121c2015-10-20 22:59:33 -0700393
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700394 .. code-block:: python
Bill Wendlingf09121c2015-10-20 22:59:33 -0700395
396 config = {
397 'key1':
398 'value1',
399 'key2': value1 +
400 value2,
401 }
402
403``INDENT_WIDTH``
404 The number of columns to use for indentation.
405
406``JOIN_MULTIPLE_LINES``
407 Join short lines into one line. E.g., single line ``if`` statements.
408
Bill Wendling9dc79082016-05-10 00:23:53 -0700409``SPACES_AROUND_POWER_OPERATOR``
410 Set to ``True`` to prefer using spaces around ``**``.
411
Jiri Kuncarf14bd172017-07-21 09:45:31 +0200412``NO_SPACES_AROUND_SELECTED_BINARY_OPERATORS``
413 Do not include spaces around selected binary operators. For example:
414
415 .. code-block:: python
416
417 1 + 2 * 3 - 4 / 5
418
419 will be formatted as follows when configured with a value ``"*,/"``:
420
421 .. code-block:: python
422
423 1 + 2*3 - 4/5
424
Alexander Lenz5fda36a2016-08-26 17:27:57 +0200425``SPACES_AROUND_DEFAULT_OR_NAMED_ASSIGN``
426 Set to ``True`` to prefer spaces around the assignment operator for default
427 or keyword arguments.
428
Bill Wendlingf09121c2015-10-20 22:59:33 -0700429``SPACES_BEFORE_COMMENT``
430 The number of spaces required before a trailing comment.
431
Bill Wendling996c3ee2016-05-25 23:52:24 -0700432``SPACE_BETWEEN_ENDING_COMMA_AND_CLOSING_BRACKET``
433 Insert a space between the ending comma and closing bracket of a list, etc.
434
Bill Wendling982c5b32016-05-24 00:47:44 -0700435``SPLIT_ARGUMENTS_WHEN_COMMA_TERMINATED``
436 Split before arguments if the argument list is terminated by a comma.
437
Bill Wendlingf09121c2015-10-20 22:59:33 -0700438``SPLIT_BEFORE_BITWISE_OPERATOR``
439 Set to ``True`` to prefer splitting before ``&``, ``|`` or ``^`` rather
440 than after.
441
Bill Wendling0e9b3212017-01-31 14:41:00 -0800442``SPLIT_BEFORE_DICT_SET_GENERATOR``
443 Split before a dictionary or set generator (comp_for). For example, note
444 the split before the ``for``:
445
446 .. code-block:: python
447
448 foo = {
449 variable: 'Hello world, have a nice day!'
450 for variable in bar if variable != 42
451 }
452
Bill Wendling6113e7e2017-10-09 01:11:38 -0700453``SPLIT_BEFORE_EXPRESSION_AFTER_OPENING_PAREN``
454 Split after the opening paren which surrounds an expression if it doesn't
455 fit on a single line.
456
Bill Wendling996c3ee2016-05-25 23:52:24 -0700457``SPLIT_BEFORE_FIRST_ARGUMENT``
458 If an argument / parameter list is going to be split, then split before the
459 first argument.
460
Bill Wendlingf09121c2015-10-20 22:59:33 -0700461``SPLIT_BEFORE_LOGICAL_OPERATOR``
462 Set to ``True`` to prefer splitting before ``and`` or ``or`` rather than
463 after.
464
465``SPLIT_BEFORE_NAMED_ASSIGNS``
466 Split named assignments onto individual lines.
467
Matthew Suozzo4a3b6332017-11-01 17:38:37 -0400468``SPLIT_COMPLEX_COMPREHENSION``
469 For list comprehensions and generator expressions with multiple clauses
delirious-lettuceb795f6d2018-01-16 20:38:46 -0700470 (e.g multiple "for" calls, "if" filter expressions) and which need to be
Matthew Suozzo4a3b6332017-11-01 17:38:37 -0400471 reflowed, split each clause onto its own line. For example:
472
473 .. code-block:: python
474
475 result = [
476 a_var + b_var for a_var in xrange(1000) for b_var in xrange(1000)
477 if a_var % b_var]
478
479 would reformat to something like:
480
481 .. code-block:: python
482
483 result = [
484 a_var + b_var
485 for a_var in xrange(1000)
486 for b_var in xrange(1000)
487 if a_var % b_var]
488
Bill Wendlingf09121c2015-10-20 22:59:33 -0700489``SPLIT_PENALTY_AFTER_OPENING_BRACKET``
490 The penalty for splitting right after the opening bracket.
491
492``SPLIT_PENALTY_AFTER_UNARY_OPERATOR``
493 The penalty for splitting the line after a unary operator.
494
Bill Wendling996c3ee2016-05-25 23:52:24 -0700495``SPLIT_PENALTY_BEFORE_IF_EXPR``
496 The penalty for splitting right before an ``if`` expression.
497
Bill Wendlingf09121c2015-10-20 22:59:33 -0700498``SPLIT_PENALTY_BITWISE_OPERATOR``
499 The penalty of splitting the line around the ``&``, ``|``, and ``^``
500 operators.
501
Matthew Suozzo3a0f6e72017-11-01 17:40:57 -0400502``SPLIT_PENALTY_COMPREHENSION``
503 The penalty for splitting a list comprehension or generator expression.
504
Bill Wendlingf09121c2015-10-20 22:59:33 -0700505``SPLIT_PENALTY_EXCESS_CHARACTER``
506 The penalty for characters over the column limit.
507
508``SPLIT_PENALTY_FOR_ADDED_LINE_SPLIT``
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700509 The penalty incurred by adding a line split to the unwrapped line. The more
510 line splits added the higher the penalty.
Bill Wendlingf09121c2015-10-20 22:59:33 -0700511
512``SPLIT_PENALTY_IMPORT_NAMES``
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700513 The penalty of splitting a list of ``import as`` names. For example:
Bill Wendlingf09121c2015-10-20 22:59:33 -0700514
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700515 .. code-block:: python
Bill Wendlingf09121c2015-10-20 22:59:33 -0700516
517 from a_very_long_or_indented_module_name_yada_yad import (long_argument_1,
518 long_argument_2,
519 long_argument_3)
520
521 would reformat to something like:
522
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700523 .. code-block:: python
Bill Wendlingf09121c2015-10-20 22:59:33 -0700524
525 from a_very_long_or_indented_module_name_yada_yad import (
526 long_argument_1, long_argument_2, long_argument_3)
527
528``SPLIT_PENALTY_LOGICAL_OPERATOR``
529 The penalty of splitting the line around the ``and`` and ``or`` operators.
530
Draconye582d632016-06-05 11:48:26 +0200531``USE_TABS``
532 Use the Tab character for indentation.
533
Bill Wendling8fb9c482015-03-29 17:32:07 -0700534(Potentially) Frequently Asked Questions
535========================================
536
537Why does YAPF destroy my awesome formatting?
538--------------------------------------------
539
540YAPF tries very hard to get the formatting correct. But for some code, it won't
541be as good as hand-formatting. In particular, large data literals may become
542horribly disfigured under YAPF.
543
mlimber8af5baf2017-11-09 13:53:22 -0500544The reasons for this are manyfold. In short, YAPF is simply a tool to help
Bill Wendling8fb9c482015-03-29 17:32:07 -0700545with development. It will format things to coincide with the style guide, but
546that may not equate with readability.
547
548What can be done to alleviate this situation is to indicate regions YAPF should
549ignore when reformatting something:
550
551.. code-block:: python
552
553 # yapf: disable
554 FOO = {
555 # ... some very large, complex data literal.
556 }
557
558 BAR = [
559 # ... another large data literal.
560 ]
561 # yapf: enable
562
563You can also disable formatting for a single literal like this:
564
565.. code-block:: python
566
567 BAZ = {
Scott Sandersoneda4e262015-07-05 21:10:06 -0400568 (1, 2, 3, 4),
569 (5, 6, 7, 8),
570 (9, 10, 11, 12),
Bill Wendling8fb9c482015-03-29 17:32:07 -0700571 } # yapf: disable
572
Łukasz Langa94089872015-09-22 16:02:26 -0700573To preserve the nice dedented closing brackets, use the
574``dedent_closing_brackets`` in your style. Note that in this case all
575brackets, including function definitions and calls, are going to use
576that style. This provides consistency across the formatted codebase.
577
Bill Wendling7d623452015-03-18 13:36:07 -0700578Why Not Improve Existing Tools?
Bill Wendling8fb9c482015-03-29 17:32:07 -0700579-------------------------------
Bill Wendling7d623452015-03-18 13:36:07 -0700580
581We wanted to use clang-format's reformatting algorithm. It's very powerful and
582designed to come up with the best formatting possible. Existing tools were
583created with different goals in mind, and would require extensive modifications
584to convert to using clang-format's algorithm.
585
Bill Wendling7d623452015-03-18 13:36:07 -0700586Can I Use YAPF In My Program?
Bill Wendling8fb9c482015-03-29 17:32:07 -0700587-----------------------------
Bill Wendling7d623452015-03-18 13:36:07 -0700588
589Please do! YAPF was designed to be used as a library as well as a command line
590tool. This means that a tool or IDE plugin is free to use YAPF.
591
Bill Wendlingf09121c2015-10-20 22:59:33 -0700592
Bill Wendling7d623452015-03-18 13:36:07 -0700593Gory Details
594============
595
596Algorithm Design
597----------------
598
Eli Benderskyd08130d2015-03-19 05:20:46 -0700599The main data structure in YAPF is the ``UnwrappedLine`` object. It holds a list
600of ``FormatToken``\s, that we would want to place on a single line if there were
601no column limit. An exception being a comment in the middle of an expression
Bill Wendling7d623452015-03-18 13:36:07 -0700602statement will force the line to be formatted on more than one line. The
Eli Benderskyd08130d2015-03-19 05:20:46 -0700603formatter works on one ``UnwrappedLine`` object at a time.
Bill Wendling7d623452015-03-18 13:36:07 -0700604
Eli Benderskyd08130d2015-03-19 05:20:46 -0700605An ``UnwrappedLine`` typically won't affect the formatting of lines before or
606after it. There is a part of the algorithm that may join two or more
607``UnwrappedLine``\s into one line. For instance, an if-then statement with a
Bill Wendlingf5e50b62015-03-28 23:38:12 -0700608short body can be placed on a single line:
609
610.. code-block:: python
Bill Wendling7d623452015-03-18 13:36:07 -0700611
612 if a == 42: continue
613
614YAPF's formatting algorithm creates a weighted tree that acts as the solution
615space for the algorithm. Each node in the tree represents the result of a
616formatting decision --- i.e., whether to split or not to split before a token.
617Each formatting decision has a cost associated with it. Therefore, the cost is
618realized on the edge between two nodes. (In reality, the weighted tree doesn't
619have separate edge objects, so the cost resides on the nodes themselves.)
620
621For example, take the following Python code snippet. For the sake of this
622example, assume that line (1) violates the column limit restriction and needs to
623be reformatted.
624
Bill Wendlingfa22c892015-03-18 13:42:25 -0700625.. code-block:: python
Bill Wendling7d623452015-03-18 13:36:07 -0700626
Bill Wendlingfa22c892015-03-18 13:42:25 -0700627 def xxxxxxxxxxx(aaaaaaaaaaaa, bbbbbbbbb, cccccccc, dddddddd, eeeeee): # 1
628 pass # 2
Bill Wendling7d623452015-03-18 13:36:07 -0700629
630For line (1), the algorithm will build a tree where each node (a
Eli Benderskyd08130d2015-03-19 05:20:46 -0700631``FormattingDecisionState`` object) is the state of the line at that token given
632the decision to split before the token or not. Note: the ``FormatDecisionState``
633objects are copied by value so each node in the graph is unique and a change in
634one doesn't affect other nodes.
Bill Wendling7d623452015-03-18 13:36:07 -0700635
Bill Wendlingfa22c892015-03-18 13:42:25 -0700636Heuristics are used to determine the costs of splitting or not splitting.
637Because a node holds the state of the tree up to a token's insertion, it can
638easily determine if a splitting decision will violate one of the style
Bill Wendling7d623452015-03-18 13:36:07 -0700639requirements. For instance, the heuristic is able to apply an extra penalty to
640the edge when not splitting between the previous token and the one being added.
641
642There are some instances where we will never want to split the line, because
643doing so will always be detrimental (i.e., it will require a backslash-newline,
644which is very rarely desirable). For line (1), we will never want to split the
Eli Benderskyd08130d2015-03-19 05:20:46 -0700645first three tokens: ``def``, ``xxxxxxxxxxx``, and ``(``. Nor will we want to
646split between the ``)`` and the ``:`` at the end. These regions are said to be
647"unbreakable." This is reflected in the tree by there not being a "split"
Bill Wendling7d623452015-03-18 13:36:07 -0700648decision (left hand branch) within the unbreakable region.
649
650Now that we have the tree, we determine what the "best" formatting is by finding
651the path through the tree with the lowest cost.
652
653And that's it!