blob: 28706589c2b80590441c6a558c63ca4abd27f08e [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é Padilla2774c1b2017-12-19 16:59:52 -050039Try out YAPF with this `online demo <https://yapf.herokuapp.com>`_.
40
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
Eli Benderskya7bfe7e2015-04-05 06:33:18 -070081YAPF supports Python 2.7 and 3.4.1+.
Eli Bendersky5eb88232015-03-27 06:27:11 -070082
83YAPF requires the code it formats to be valid Python for the version YAPF itself
84runs under. Therefore, if you format Python 3 code with YAPF, run YAPF itself
85under Python 3 (and similarly for Python 2).
86
Bill Wendlingf09121c2015-10-20 22:59:33 -070087
Bill Wendling7d623452015-03-18 13:36:07 -070088Usage
89=====
90
Bill Wendlingfa22c892015-03-18 13:42:25 -070091Options::
Bill Wendling7d623452015-03-18 13:36:07 -070092
Bill Wendlingf09121c2015-10-20 22:59:33 -070093 usage: yapf [-h] [-v] [-d | -i] [-r | -l START-END] [-e PATTERN]
Diogo de Campos2f246c02016-10-06 14:04:38 +020094 [--style STYLE] [--style-help] [--no-local-style] [-p]
Bill Wendling7bfc0a92017-10-16 03:22:19 -070095 [-vv]
Bill Wendlingf09121c2015-10-20 22:59:33 -070096 [files [files ...]]
Bill Wendling7d623452015-03-18 13:36:07 -070097
Bill Wendlingfa22c892015-03-18 13:42:25 -070098 Formatter for Python code.
Bill Wendling7d623452015-03-18 13:36:07 -070099
Bill Wendlingfa22c892015-03-18 13:42:25 -0700100 positional arguments:
101 files
102
103 optional arguments:
104 -h, --help show this help message and exit
Bill Wendlingf09121c2015-10-20 22:59:33 -0700105 -v, --version show version number and exit
106 -d, --diff print the diff for the fixed source
107 -i, --in-place make changes to files in place
108 -r, --recursive run recursively over directories
109 -l START-END, --lines START-END
110 range of lines to reformat, one-based
111 -e PATTERN, --exclude PATTERN
112 patterns for files to exclude from formatting
Eli Bendersky83d2bd02015-03-23 06:33:48 -0700113 --style STYLE specify formatting style: either a style name (for
114 example "pep8" or "google"), or the name of a file
Sam Clegg5170c3a2015-04-16 12:18:58 -0700115 with style settings. The default is pep8 unless a
Peter Ludemann827260c2017-12-20 19:54:27 -0800116 .style.yapf or setup.cfg file located in the same
117 directory as the source or one of its parent
118 directories (for stdin, the current directory is
119 used).
Bill Wendling7bfc0a92017-10-16 03:22:19 -0700120 --style-help show style settings and exit; this output can be saved
121 to .style.yapf to make your settings permanent
122 --no-local-style don't search for local style definition
Diogo de Campos2f246c02016-10-06 14:04:38 +0200123 -p, --parallel Run yapf in parallel when formatting multiple files.
124 Requires concurrent.futures in Python 2.X
Bill Wendling7bfc0a92017-10-16 03:22:19 -0700125 -vv, --verbose Print out file names while processing
Bill Wendlingf09121c2015-10-20 22:59:33 -0700126
Bill Wendling7d623452015-03-18 13:36:07 -0700127
Eli Bendersky83d2bd02015-03-23 06:33:48 -0700128Formatting style
Bill Wendlingf5e50b62015-03-28 23:38:12 -0700129================
Eli Bendersky83d2bd02015-03-23 06:33:48 -0700130
131The formatting style used by YAPF is configurable and there are many "knobs"
132that can be used to tune how YAPF does formatting. See the ``style.py`` module
133for the full list.
134
Bill Wendlingc0167792015-04-02 01:58:39 -0700135To control the style, run YAPF with the ``--style`` argument. It accepts one of
136the predefined styles (e.g., ``pep8`` or ``google``), a path to a configuration
137file that specifies the desired style, or a dictionary of key/value pairs.
138
139The config file is a simple listing of (case-insensitive) ``key = value`` pairs
Bill Wendling6e8ca7b2015-10-25 01:16:43 -0700140with a ``[style]`` heading. For example:
141
Bill Wendling4f96aab2016-07-16 15:52:51 -0700142.. code-block::
Eli Bendersky83d2bd02015-03-23 06:33:48 -0700143
144 [style]
145 based_on_style = pep8
146 spaces_before_comment = 4
147 split_before_logical_operator = true
148
149The ``based_on_style`` setting determines which of the predefined styles this
150custom style is based on (think of it like subclassing).
Bill Wendling7d623452015-03-18 13:36:07 -0700151
Bill Wendlingc0167792015-04-02 01:58:39 -0700152It's also possible to do the same on the command line with a dictionary. For
Bill Wendling6e8ca7b2015-10-25 01:16:43 -0700153example:
154
Bill Wendling4f96aab2016-07-16 15:52:51 -0700155.. code-block::
Bill Wendlingc0167792015-04-02 01:58:39 -0700156
Bill Wendlingf09121c2015-10-20 22:59:33 -0700157 --style='{based_on_style: chromium, indent_width: 4}'
Bill Wendlingc0167792015-04-02 01:58:39 -0700158
Bill Wendlingf09121c2015-10-20 22:59:33 -0700159This will take the ``chromium`` base style and modify it to have four space
Bill Wendlingc0167792015-04-02 01:58:39 -0700160indentations.
161
Bill Wendling169790e2015-10-25 03:13:13 -0700162YAPF will search for the formatting style in the following manner:
163
1641. Specified on the command line
Joshua Moravecd8d15af2015-11-05 13:16:46 -06001652. In the `[style]` section of a `.style.yapf` file in either the current
Bill Wendling169790e2015-10-25 03:13:13 -0700166 directory or one of its parent directories.
Bill Wendling821a36f2016-07-13 23:02:16 -07001673. In the `[yapf]` section of a `setup.cfg` file in either the current
Bill Wendling169790e2015-10-25 03:13:13 -0700168 directory or one of its parent directories.
1694. In the `~/.config/yapf/style` file in your home directory.
170
171If none of those files are found, the default style is used (PEP8).
172
Bill Wendlingf09121c2015-10-20 22:59:33 -0700173
Bill Wendlingf5e50b62015-03-28 23:38:12 -0700174Example
175=======
176
Sam Clegg4357fa32015-04-08 12:21:46 -0700177An example of the type of formatting that YAPF can do, it will take this ugly
178code:
Bill Wendlingf5e50b62015-03-28 23:38:12 -0700179
180.. code-block:: python
181
182 x = { 'a':37,'b':42,
183
184 'c':927}
185
186 y = 'hello ''world'
187 z = 'hello '+'world'
188 a = 'hello {}'.format('world')
189 class foo ( object ):
190 def f (self ):
191 return 37*-+2
192 def g(self, x,y=42):
193 return y
194 def f ( a ) :
195 return 37+-+a[42-x : y**3]
196
Bill Wendling8fb9c482015-03-29 17:32:07 -0700197and reformat it into:
Bill Wendlingf5e50b62015-03-28 23:38:12 -0700198
199.. code-block:: python
200
201 x = {'a': 37, 'b': 42, 'c': 927}
202
203 y = 'hello ' 'world'
204 z = 'hello ' + 'world'
205 a = 'hello {}'.format('world')
206
207
208 class foo(object):
Bill Wendling5632e672015-03-29 17:06:07 -0700209 def f(self):
210 return 37 * -+2
Bill Wendlingf5e50b62015-03-28 23:38:12 -0700211
Bill Wendling5632e672015-03-29 17:06:07 -0700212 def g(self, x, y=42):
213 return y
Bill Wendlingf5e50b62015-03-28 23:38:12 -0700214
215
216 def f(a):
Bill Wendling8d8f5122015-10-16 11:46:23 -0700217 return 37 + -+a[42 - x:y**3]
Bill Wendlingf5e50b62015-03-28 23:38:12 -0700218
Bill Wendlingf09121c2015-10-20 22:59:33 -0700219
Andy Haydena00a6bf2015-06-15 18:47:41 -0700220Example as a module
221===================
222
Andy Hayden4af71682015-06-17 15:42:43 -0700223The two main APIs for calling yapf are ``FormatCode`` and ``FormatFile``, these
224share several arguments which are described below:
Andy Haydena00a6bf2015-06-15 18:47:41 -0700225
226.. code-block:: python
227
srinivasanramarajucfa7ead2017-02-14 00:06:58 -0800228 >>> from yapf.yapflib.yapf_api import FormatCode # reformat a string of code
Łukasz Langa94089872015-09-22 16:02:26 -0700229
Andy Haydena00a6bf2015-06-15 18:47:41 -0700230 >>> FormatCode("f ( a = 1, b = 2 )")
231 'f(a=1, b=2)\n'
232
Andy Hayden4af71682015-06-17 15:42:43 -0700233A ``style_config`` argument: Either a style name or a path to a file that contains
Andy Haydena00a6bf2015-06-15 18:47:41 -0700234formatting style settings. If None is specified, use the default style
235as set in ``style.DEFAULT_STYLE_FACTORY``.
236
237.. code-block:: python
238
239 >>> FormatCode("def g():\n return True", style_config='pep8')
240 'def g():\n return True\n'
241
Andy Haydena00a6bf2015-06-15 18:47:41 -0700242A ``lines`` argument: A list of tuples of lines (ints), [start, end],
243that we want to format. The lines are 1-based indexed. It can be used by
244third-party code (e.g., IDEs) when reformatting a snippet of code rather
245than a whole file.
246
247.. code-block:: python
248
249 >>> FormatCode("def g( ):\n a=1\n b = 2\n return a==b", lines=[(1, 1), (2, 3)])
250 'def g():\n a = 1\n b = 2\n return a==b\n'
251
252A ``print_diff`` (bool): Instead of returning the reformatted source, return a
253diff that turns the formatted source into reformatter source.
254
255.. code-block:: python
256
257 >>> print(FormatCode("a==b", filename="foo.py", print_diff=True))
Bill Wendlingb8645ea2015-06-30 22:27:56 -0700258 --- foo.py (original)
259 +++ foo.py (reformatted)
Andy Haydena00a6bf2015-06-15 18:47:41 -0700260 @@ -1 +1 @@
261 -a==b
262 +a == b
263
Andy Hayden4af71682015-06-17 15:42:43 -0700264Note: the ``filename`` argument for ``FormatCode`` is what is inserted into
265the diff, the default is ``<unknown>``.
Andy Haydena00a6bf2015-06-15 18:47:41 -0700266
267``FormatFile`` returns reformatted code from the passed file along with its encoding:
268
269.. code-block:: python
270
srinivasanramarajucfa7ead2017-02-14 00:06:58 -0800271 >>> from yapf.yapflib.yapf_api import FormatFile # reformat a file
Andy Hayden4af71682015-06-17 15:42:43 -0700272
Andy Haydena00a6bf2015-06-15 18:47:41 -0700273 >>> print(open("foo.py").read()) # contents of file
274 a==b
275
276 >>> FormatFile("foo.py")
Andy Hayden4af71682015-06-17 15:42:43 -0700277 ('a == b\n', 'utf-8')
278
Bill Wendlingcfbb1242015-09-20 12:08:18 -0700279The ``in-place`` argument saves the reformatted code back to the file:
Andy Hayden4af71682015-06-17 15:42:43 -0700280
281.. code-block:: python
282
283 >>> FormatFile("foo.py", in_place=True)
284 (None, 'utf-8')
285
286 >>> print(open("foo.py").read()) # contents of file (now fixed)
287 a == b
288
Andy Haydena00a6bf2015-06-15 18:47:41 -0700289
Bill Wendlingf09121c2015-10-20 22:59:33 -0700290Knobs
291=====
292
293``ALIGN_CLOSING_BRACKET_WITH_VISUAL_INDENT``
294 Align closing bracket with visual indentation.
295
Bill Wendling996c3ee2016-05-25 23:52:24 -0700296``ALLOW_MULTILINE_LAMBDAS``
297 Allow lambdas to be formatted on more than one line.
298
Bill Wendling8d321362017-02-05 18:29:26 -0800299``ALLOW_MULTILINE_DICTIONARY_KEYS``
300 Allow dictionary keys to exist on multiple lines. For example:
301
302 .. code-block:: python
303
304 x = {
305 ('this is the first element of a tuple',
306 'this is the second element of a tuple'):
307 value,
308 }
309
Bill Wendling8a3b71f2017-08-26 02:34:03 -0700310``ALLOW_SPLIT_BEFORE_DICT_VALUE``
311 Allow splits before the dictionary value.
312
Bill Wendlingf09121c2015-10-20 22:59:33 -0700313``BLANK_LINE_BEFORE_NESTED_CLASS_OR_DEF``
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700314 Insert a blank line before a ``def`` or ``class`` immediately nested within
Bill Wendling996c3ee2016-05-25 23:52:24 -0700315 another ``def`` or ``class``. For example:
Bill Wendlingf09121c2015-10-20 22:59:33 -0700316
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700317 .. code-block:: python
Bill Wendlingf09121c2015-10-20 22:59:33 -0700318
319 class Foo:
320 # <------ this blank line
321 def method():
322 pass
323
Bill Wendling9f497522017-02-04 04:39:47 -0800324``BLANK_LINE_BEFORE_CLASS_DOCSTRING``
325 Insert a blank line before a class-level docstring.
326
Ben Plotnick7e088292016-06-09 18:29:56 -0700327``COALESCE_BRACKETS``
328 Do not split consecutive brackets. Only relevant when
329 ``DEDENT_CLOSING_BRACKETS`` is set. For example:
330
331 .. code-block:: python
332
333 call_func_that_takes_a_dict(
334 {
335 'key1': 'value1',
336 'key2': 'value2',
337 }
338 )
339
340 would reformat to:
341
342 .. code-block:: python
343
344 call_func_that_takes_a_dict({
345 'key1': 'value1',
346 'key2': 'value2',
347 })
348
349
Bill Wendlingf09121c2015-10-20 22:59:33 -0700350``COLUMN_LIMIT``
James Broadheadf4dd8042016-01-07 14:40:19 +0000351 The column limit (or max line-length)
Bill Wendlingf09121c2015-10-20 22:59:33 -0700352
353``CONTINUATION_INDENT_WIDTH``
354 Indent width used for line continuations.
355
356``DEDENT_CLOSING_BRACKETS``
357 Put closing brackets on a separate line, dedented, if the bracketed
358 expression can't fit in a single line. Applies to all kinds of brackets,
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700359 including function definitions and calls. For example:
Bill Wendlingf09121c2015-10-20 22:59:33 -0700360
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700361 .. code-block:: python
Bill Wendlingf09121c2015-10-20 22:59:33 -0700362
363 config = {
364 'key1': 'value1',
365 'key2': 'value2',
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700366 } # <--- this bracket is dedented and on a separate line
Bill Wendlingf09121c2015-10-20 22:59:33 -0700367
368 time_series = self.remote_client.query_entity_counters(
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700369 entity='dev3246.region1',
370 key='dns.query_latency_tcp',
371 transform=Transformation.AVERAGE(window=timedelta(seconds=60)),
372 start_ts=now()-timedelta(days=3),
373 end_ts=now(),
374 ) # <--- this bracket is dedented and on a separate line
Bill Wendlingf09121c2015-10-20 22:59:33 -0700375
Bill Wendling0e9b3212017-01-31 14:41:00 -0800376``EACH_DICT_ENTRY_ON_SEPARATE_LINE``
377 Place each dictionary entry onto its own line.
378
Bill Wendlingf09121c2015-10-20 22:59:33 -0700379``I18N_COMMENT``
380 The regex for an internationalization comment. The presence of this comment
381 stops reformatting of that line, because the comments are required to be
382 next to the string they translate.
383
384``I18N_FUNCTION_CALL``
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700385 The internationalization function call names. The presence of this function
Samuel Dion-Girardeau5ae63492016-09-08 21:01:20 -0400386 stops reformatting on that line, because the string it has cannot be moved
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700387 away from the i18n comment.
Bill Wendlingf09121c2015-10-20 22:59:33 -0700388
389``INDENT_DICTIONARY_VALUE``
390 Indent the dictionary value if it cannot fit on the same line as the
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700391 dictionary key. For example:
Bill Wendlingf09121c2015-10-20 22:59:33 -0700392
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700393 .. code-block:: python
Bill Wendlingf09121c2015-10-20 22:59:33 -0700394
395 config = {
396 'key1':
397 'value1',
398 'key2': value1 +
399 value2,
400 }
401
402``INDENT_WIDTH``
403 The number of columns to use for indentation.
404
405``JOIN_MULTIPLE_LINES``
406 Join short lines into one line. E.g., single line ``if`` statements.
407
Bill Wendling9dc79082016-05-10 00:23:53 -0700408``SPACES_AROUND_POWER_OPERATOR``
409 Set to ``True`` to prefer using spaces around ``**``.
410
Jiri Kuncarf14bd172017-07-21 09:45:31 +0200411``NO_SPACES_AROUND_SELECTED_BINARY_OPERATORS``
412 Do not include spaces around selected binary operators. For example:
413
414 .. code-block:: python
415
416 1 + 2 * 3 - 4 / 5
417
418 will be formatted as follows when configured with a value ``"*,/"``:
419
420 .. code-block:: python
421
422 1 + 2*3 - 4/5
423
Alexander Lenz5fda36a2016-08-26 17:27:57 +0200424``SPACES_AROUND_DEFAULT_OR_NAMED_ASSIGN``
425 Set to ``True`` to prefer spaces around the assignment operator for default
426 or keyword arguments.
427
Bill Wendlingf09121c2015-10-20 22:59:33 -0700428``SPACES_BEFORE_COMMENT``
429 The number of spaces required before a trailing comment.
430
Bill Wendling996c3ee2016-05-25 23:52:24 -0700431``SPACE_BETWEEN_ENDING_COMMA_AND_CLOSING_BRACKET``
432 Insert a space between the ending comma and closing bracket of a list, etc.
433
Bill Wendling982c5b32016-05-24 00:47:44 -0700434``SPLIT_ARGUMENTS_WHEN_COMMA_TERMINATED``
435 Split before arguments if the argument list is terminated by a comma.
436
Bill Wendlingf09121c2015-10-20 22:59:33 -0700437``SPLIT_BEFORE_BITWISE_OPERATOR``
438 Set to ``True`` to prefer splitting before ``&``, ``|`` or ``^`` rather
439 than after.
440
Bill Wendling0e9b3212017-01-31 14:41:00 -0800441``SPLIT_BEFORE_DICT_SET_GENERATOR``
442 Split before a dictionary or set generator (comp_for). For example, note
443 the split before the ``for``:
444
445 .. code-block:: python
446
447 foo = {
448 variable: 'Hello world, have a nice day!'
449 for variable in bar if variable != 42
450 }
451
Bill Wendling6113e7e2017-10-09 01:11:38 -0700452``SPLIT_BEFORE_EXPRESSION_AFTER_OPENING_PAREN``
453 Split after the opening paren which surrounds an expression if it doesn't
454 fit on a single line.
455
Bill Wendling996c3ee2016-05-25 23:52:24 -0700456``SPLIT_BEFORE_FIRST_ARGUMENT``
457 If an argument / parameter list is going to be split, then split before the
458 first argument.
459
Bill Wendlingf09121c2015-10-20 22:59:33 -0700460``SPLIT_BEFORE_LOGICAL_OPERATOR``
461 Set to ``True`` to prefer splitting before ``and`` or ``or`` rather than
462 after.
463
464``SPLIT_BEFORE_NAMED_ASSIGNS``
465 Split named assignments onto individual lines.
466
Matthew Suozzo4a3b6332017-11-01 17:38:37 -0400467``SPLIT_COMPLEX_COMPREHENSION``
468 For list comprehensions and generator expressions with multiple clauses
469 (e.g mutiple "for" calls, "if" filter expressions) and which need to be
470 reflowed, split each clause onto its own line. For example:
471
472 .. code-block:: python
473
474 result = [
475 a_var + b_var for a_var in xrange(1000) for b_var in xrange(1000)
476 if a_var % b_var]
477
478 would reformat to something like:
479
480 .. code-block:: python
481
482 result = [
483 a_var + b_var
484 for a_var in xrange(1000)
485 for b_var in xrange(1000)
486 if a_var % b_var]
487
Bill Wendlingf09121c2015-10-20 22:59:33 -0700488``SPLIT_PENALTY_AFTER_OPENING_BRACKET``
489 The penalty for splitting right after the opening bracket.
490
491``SPLIT_PENALTY_AFTER_UNARY_OPERATOR``
492 The penalty for splitting the line after a unary operator.
493
Bill Wendling996c3ee2016-05-25 23:52:24 -0700494``SPLIT_PENALTY_BEFORE_IF_EXPR``
495 The penalty for splitting right before an ``if`` expression.
496
Bill Wendlingf09121c2015-10-20 22:59:33 -0700497``SPLIT_PENALTY_BITWISE_OPERATOR``
498 The penalty of splitting the line around the ``&``, ``|``, and ``^``
499 operators.
500
Matthew Suozzo3a0f6e72017-11-01 17:40:57 -0400501``SPLIT_PENALTY_COMPREHENSION``
502 The penalty for splitting a list comprehension or generator expression.
503
Bill Wendlingf09121c2015-10-20 22:59:33 -0700504``SPLIT_PENALTY_EXCESS_CHARACTER``
505 The penalty for characters over the column limit.
506
507``SPLIT_PENALTY_FOR_ADDED_LINE_SPLIT``
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700508 The penalty incurred by adding a line split to the unwrapped line. The more
509 line splits added the higher the penalty.
Bill Wendlingf09121c2015-10-20 22:59:33 -0700510
511``SPLIT_PENALTY_IMPORT_NAMES``
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700512 The penalty of splitting a list of ``import as`` names. For example:
Bill Wendlingf09121c2015-10-20 22:59:33 -0700513
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700514 .. code-block:: python
Bill Wendlingf09121c2015-10-20 22:59:33 -0700515
516 from a_very_long_or_indented_module_name_yada_yad import (long_argument_1,
517 long_argument_2,
518 long_argument_3)
519
520 would reformat to something like:
521
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700522 .. code-block:: python
Bill Wendlingf09121c2015-10-20 22:59:33 -0700523
524 from a_very_long_or_indented_module_name_yada_yad import (
525 long_argument_1, long_argument_2, long_argument_3)
526
527``SPLIT_PENALTY_LOGICAL_OPERATOR``
528 The penalty of splitting the line around the ``and`` and ``or`` operators.
529
Draconye582d632016-06-05 11:48:26 +0200530``USE_TABS``
531 Use the Tab character for indentation.
532
Bill Wendling8fb9c482015-03-29 17:32:07 -0700533(Potentially) Frequently Asked Questions
534========================================
535
536Why does YAPF destroy my awesome formatting?
537--------------------------------------------
538
539YAPF tries very hard to get the formatting correct. But for some code, it won't
540be as good as hand-formatting. In particular, large data literals may become
541horribly disfigured under YAPF.
542
mlimber8af5baf2017-11-09 13:53:22 -0500543The reasons for this are manyfold. In short, YAPF is simply a tool to help
Bill Wendling8fb9c482015-03-29 17:32:07 -0700544with development. It will format things to coincide with the style guide, but
545that may not equate with readability.
546
547What can be done to alleviate this situation is to indicate regions YAPF should
548ignore when reformatting something:
549
550.. code-block:: python
551
552 # yapf: disable
553 FOO = {
554 # ... some very large, complex data literal.
555 }
556
557 BAR = [
558 # ... another large data literal.
559 ]
560 # yapf: enable
561
562You can also disable formatting for a single literal like this:
563
564.. code-block:: python
565
566 BAZ = {
Scott Sandersoneda4e262015-07-05 21:10:06 -0400567 (1, 2, 3, 4),
568 (5, 6, 7, 8),
569 (9, 10, 11, 12),
Bill Wendling8fb9c482015-03-29 17:32:07 -0700570 } # yapf: disable
571
Łukasz Langa94089872015-09-22 16:02:26 -0700572To preserve the nice dedented closing brackets, use the
573``dedent_closing_brackets`` in your style. Note that in this case all
574brackets, including function definitions and calls, are going to use
575that style. This provides consistency across the formatted codebase.
576
Bill Wendling7d623452015-03-18 13:36:07 -0700577Why Not Improve Existing Tools?
Bill Wendling8fb9c482015-03-29 17:32:07 -0700578-------------------------------
Bill Wendling7d623452015-03-18 13:36:07 -0700579
580We wanted to use clang-format's reformatting algorithm. It's very powerful and
581designed to come up with the best formatting possible. Existing tools were
582created with different goals in mind, and would require extensive modifications
583to convert to using clang-format's algorithm.
584
Bill Wendling7d623452015-03-18 13:36:07 -0700585Can I Use YAPF In My Program?
Bill Wendling8fb9c482015-03-29 17:32:07 -0700586-----------------------------
Bill Wendling7d623452015-03-18 13:36:07 -0700587
588Please do! YAPF was designed to be used as a library as well as a command line
589tool. This means that a tool or IDE plugin is free to use YAPF.
590
Bill Wendlingf09121c2015-10-20 22:59:33 -0700591
Bill Wendling7d623452015-03-18 13:36:07 -0700592Gory Details
593============
594
595Algorithm Design
596----------------
597
Eli Benderskyd08130d2015-03-19 05:20:46 -0700598The main data structure in YAPF is the ``UnwrappedLine`` object. It holds a list
599of ``FormatToken``\s, that we would want to place on a single line if there were
600no column limit. An exception being a comment in the middle of an expression
Bill Wendling7d623452015-03-18 13:36:07 -0700601statement will force the line to be formatted on more than one line. The
Eli Benderskyd08130d2015-03-19 05:20:46 -0700602formatter works on one ``UnwrappedLine`` object at a time.
Bill Wendling7d623452015-03-18 13:36:07 -0700603
Eli Benderskyd08130d2015-03-19 05:20:46 -0700604An ``UnwrappedLine`` typically won't affect the formatting of lines before or
605after it. There is a part of the algorithm that may join two or more
606``UnwrappedLine``\s into one line. For instance, an if-then statement with a
Bill Wendlingf5e50b62015-03-28 23:38:12 -0700607short body can be placed on a single line:
608
609.. code-block:: python
Bill Wendling7d623452015-03-18 13:36:07 -0700610
611 if a == 42: continue
612
613YAPF's formatting algorithm creates a weighted tree that acts as the solution
614space for the algorithm. Each node in the tree represents the result of a
615formatting decision --- i.e., whether to split or not to split before a token.
616Each formatting decision has a cost associated with it. Therefore, the cost is
617realized on the edge between two nodes. (In reality, the weighted tree doesn't
618have separate edge objects, so the cost resides on the nodes themselves.)
619
620For example, take the following Python code snippet. For the sake of this
621example, assume that line (1) violates the column limit restriction and needs to
622be reformatted.
623
Bill Wendlingfa22c892015-03-18 13:42:25 -0700624.. code-block:: python
Bill Wendling7d623452015-03-18 13:36:07 -0700625
Bill Wendlingfa22c892015-03-18 13:42:25 -0700626 def xxxxxxxxxxx(aaaaaaaaaaaa, bbbbbbbbb, cccccccc, dddddddd, eeeeee): # 1
627 pass # 2
Bill Wendling7d623452015-03-18 13:36:07 -0700628
629For line (1), the algorithm will build a tree where each node (a
Eli Benderskyd08130d2015-03-19 05:20:46 -0700630``FormattingDecisionState`` object) is the state of the line at that token given
631the decision to split before the token or not. Note: the ``FormatDecisionState``
632objects are copied by value so each node in the graph is unique and a change in
633one doesn't affect other nodes.
Bill Wendling7d623452015-03-18 13:36:07 -0700634
Bill Wendlingfa22c892015-03-18 13:42:25 -0700635Heuristics are used to determine the costs of splitting or not splitting.
636Because a node holds the state of the tree up to a token's insertion, it can
637easily determine if a splitting decision will violate one of the style
Bill Wendling7d623452015-03-18 13:36:07 -0700638requirements. For instance, the heuristic is able to apply an extra penalty to
639the edge when not splitting between the previous token and the one being added.
640
641There are some instances where we will never want to split the line, because
642doing so will always be detrimental (i.e., it will require a backslash-newline,
643which is very rarely desirable). For line (1), we will never want to split the
Eli Benderskyd08130d2015-03-19 05:20:46 -0700644first three tokens: ``def``, ``xxxxxxxxxxx``, and ``(``. Nor will we want to
645split between the ``)`` and the ``:`` at the end. These regions are said to be
646"unbreakable." This is reflected in the tree by there not being a "split"
Bill Wendling7d623452015-03-18 13:36:07 -0700647decision (left hand branch) within the unbreakable region.
648
649Now that we have the tree, we determine what the "best" formatting is by finding
650the path through the tree with the lowest cost.
651
652And that's it!