blob: 6cbd0ceea40b442682f80b3dc27ce64ef445c469 [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
6 :target: http://badge.fury.io/py/yapf
7 :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
Bill Wendlingf5e50b62015-03-28 23:38:12 -070039.. footer::
Bill Wendling52e04112015-03-18 20:42:26 -070040
41 YAPF is not an official Google product (experimental or otherwise), it is
42 just code that happens to be owned by Google.
43
Bill Wendling7d623452015-03-18 13:36:07 -070044.. contents::
45
Bill Wendlingf09121c2015-10-20 22:59:33 -070046
Bill Wendling7d623452015-03-18 13:36:07 -070047Installation
48============
49
Bill Wendling6e8ca7b2015-10-25 01:16:43 -070050To install YAPF from PyPI:
51
Bill Wendling4f96aab2016-07-16 15:52:51 -070052.. code-block::
Eli Bendersky8a365362015-03-25 18:42:22 -070053
Eli Benderskye0e83c12015-04-06 20:23:30 -070054 $ pip install yapf
55
Diogo de Campos2f246c02016-10-06 14:04:38 +020056(optional) If you are using Python 2.7 and want to enable multiprocessing:
57
58.. code-block::
59
60 $ pip install futures
61
Eli Benderskye0e83c12015-04-06 20:23:30 -070062YAPF is still considered in "alpha" stage, and the released version may change
63often; therefore, the best way to keep up-to-date with the latest development
64is to clone this repository.
65
66Note that if you intend to use YAPF as a command-line tool rather than as a
67library, installation is not necessary. YAPF supports being run as a directory
68by the Python interpreter. If you cloned/unzipped YAPF into ``DIR``, it's
Bill Wendling6e8ca7b2015-10-25 01:16:43 -070069possible to run:
70
Bill Wendling4f96aab2016-07-16 15:52:51 -070071.. code-block::
Eli Bendersky07072f82015-03-23 06:41:14 -070072
Eli Benderskyb3678b32015-03-25 14:16:11 -070073 $ PYTHONPATH=DIR python DIR/yapf [options] ...
Eli Bendersky07072f82015-03-23 06:41:14 -070074
Bill Wendlingf09121c2015-10-20 22:59:33 -070075
Eli Bendersky5eb88232015-03-27 06:27:11 -070076Python versions
77===============
78
Eli Benderskya7bfe7e2015-04-05 06:33:18 -070079YAPF supports Python 2.7 and 3.4.1+.
Eli Bendersky5eb88232015-03-27 06:27:11 -070080
81YAPF requires the code it formats to be valid Python for the version YAPF itself
82runs under. Therefore, if you format Python 3 code with YAPF, run YAPF itself
83under Python 3 (and similarly for Python 2).
84
Bill Wendlingf09121c2015-10-20 22:59:33 -070085
Bill Wendling7d623452015-03-18 13:36:07 -070086Usage
87=====
88
Bill Wendlingfa22c892015-03-18 13:42:25 -070089Options::
Bill Wendling7d623452015-03-18 13:36:07 -070090
Bill Wendlingf09121c2015-10-20 22:59:33 -070091 usage: yapf [-h] [-v] [-d | -i] [-r | -l START-END] [-e PATTERN]
Diogo de Campos2f246c02016-10-06 14:04:38 +020092 [--style STYLE] [--style-help] [--no-local-style] [-p]
Bill Wendlingf09121c2015-10-20 22:59:33 -070093 [files [files ...]]
Bill Wendling7d623452015-03-18 13:36:07 -070094
Bill Wendlingfa22c892015-03-18 13:42:25 -070095 Formatter for Python code.
Bill Wendling7d623452015-03-18 13:36:07 -070096
Bill Wendlingfa22c892015-03-18 13:42:25 -070097 positional arguments:
98 files
99
100 optional arguments:
101 -h, --help show this help message and exit
Bill Wendlingf09121c2015-10-20 22:59:33 -0700102 -v, --version show version number and exit
103 -d, --diff print the diff for the fixed source
104 -i, --in-place make changes to files in place
105 -r, --recursive run recursively over directories
106 -l START-END, --lines START-END
107 range of lines to reformat, one-based
108 -e PATTERN, --exclude PATTERN
109 patterns for files to exclude from formatting
Eli Bendersky83d2bd02015-03-23 06:33:48 -0700110 --style STYLE specify formatting style: either a style name (for
111 example "pep8" or "google"), or the name of a file
Sam Clegg5170c3a2015-04-16 12:18:58 -0700112 with style settings. The default is pep8 unless a
Bill Wendling6e8ca7b2015-10-25 01:16:43 -0700113 .style.yapf or setup.cfg file located in one of the
114 parent directories of the source file (or current
115 directory for stdin)
Bill Wendlingf09121c2015-10-20 22:59:33 -0700116 --style-help show style settings and exit
117 --no-local-style don't search for local style definition (.style.yapf)
Diogo de Campos2f246c02016-10-06 14:04:38 +0200118 -p, --parallel Run yapf in parallel when formatting multiple files.
119 Requires concurrent.futures in Python 2.X
Bill Wendlingf09121c2015-10-20 22:59:33 -0700120
Bill Wendling7d623452015-03-18 13:36:07 -0700121
Eli Bendersky83d2bd02015-03-23 06:33:48 -0700122Formatting style
Bill Wendlingf5e50b62015-03-28 23:38:12 -0700123================
Eli Bendersky83d2bd02015-03-23 06:33:48 -0700124
125The formatting style used by YAPF is configurable and there are many "knobs"
126that can be used to tune how YAPF does formatting. See the ``style.py`` module
127for the full list.
128
Bill Wendlingc0167792015-04-02 01:58:39 -0700129To control the style, run YAPF with the ``--style`` argument. It accepts one of
130the predefined styles (e.g., ``pep8`` or ``google``), a path to a configuration
131file that specifies the desired style, or a dictionary of key/value pairs.
132
133The config file is a simple listing of (case-insensitive) ``key = value`` pairs
Bill Wendling6e8ca7b2015-10-25 01:16:43 -0700134with a ``[style]`` heading. For example:
135
Bill Wendling4f96aab2016-07-16 15:52:51 -0700136.. code-block::
Eli Bendersky83d2bd02015-03-23 06:33:48 -0700137
138 [style]
139 based_on_style = pep8
140 spaces_before_comment = 4
141 split_before_logical_operator = true
142
143The ``based_on_style`` setting determines which of the predefined styles this
144custom style is based on (think of it like subclassing).
Bill Wendling7d623452015-03-18 13:36:07 -0700145
Bill Wendlingc0167792015-04-02 01:58:39 -0700146It's also possible to do the same on the command line with a dictionary. For
Bill Wendling6e8ca7b2015-10-25 01:16:43 -0700147example:
148
Bill Wendling4f96aab2016-07-16 15:52:51 -0700149.. code-block::
Bill Wendlingc0167792015-04-02 01:58:39 -0700150
Bill Wendlingf09121c2015-10-20 22:59:33 -0700151 --style='{based_on_style: chromium, indent_width: 4}'
Bill Wendlingc0167792015-04-02 01:58:39 -0700152
Bill Wendlingf09121c2015-10-20 22:59:33 -0700153This will take the ``chromium`` base style and modify it to have four space
Bill Wendlingc0167792015-04-02 01:58:39 -0700154indentations.
155
Bill Wendling169790e2015-10-25 03:13:13 -0700156YAPF will search for the formatting style in the following manner:
157
1581. Specified on the command line
Joshua Moravecd8d15af2015-11-05 13:16:46 -06001592. In the `[style]` section of a `.style.yapf` file in either the current
Bill Wendling169790e2015-10-25 03:13:13 -0700160 directory or one of its parent directories.
Bill Wendling821a36f2016-07-13 23:02:16 -07001613. In the `[yapf]` section of a `setup.cfg` file in either the current
Bill Wendling169790e2015-10-25 03:13:13 -0700162 directory or one of its parent directories.
1634. In the `~/.config/yapf/style` file in your home directory.
164
165If none of those files are found, the default style is used (PEP8).
166
Bill Wendlingf09121c2015-10-20 22:59:33 -0700167
Bill Wendlingf5e50b62015-03-28 23:38:12 -0700168Example
169=======
170
Sam Clegg4357fa32015-04-08 12:21:46 -0700171An example of the type of formatting that YAPF can do, it will take this ugly
172code:
Bill Wendlingf5e50b62015-03-28 23:38:12 -0700173
174.. code-block:: python
175
176 x = { 'a':37,'b':42,
177
178 'c':927}
179
180 y = 'hello ''world'
181 z = 'hello '+'world'
182 a = 'hello {}'.format('world')
183 class foo ( object ):
184 def f (self ):
185 return 37*-+2
186 def g(self, x,y=42):
187 return y
188 def f ( a ) :
189 return 37+-+a[42-x : y**3]
190
Bill Wendling8fb9c482015-03-29 17:32:07 -0700191and reformat it into:
Bill Wendlingf5e50b62015-03-28 23:38:12 -0700192
193.. code-block:: python
194
195 x = {'a': 37, 'b': 42, 'c': 927}
196
197 y = 'hello ' 'world'
198 z = 'hello ' + 'world'
199 a = 'hello {}'.format('world')
200
201
202 class foo(object):
Bill Wendling5632e672015-03-29 17:06:07 -0700203 def f(self):
204 return 37 * -+2
Bill Wendlingf5e50b62015-03-28 23:38:12 -0700205
Bill Wendling5632e672015-03-29 17:06:07 -0700206 def g(self, x, y=42):
207 return y
Bill Wendlingf5e50b62015-03-28 23:38:12 -0700208
209
210 def f(a):
Bill Wendling8d8f5122015-10-16 11:46:23 -0700211 return 37 + -+a[42 - x:y**3]
Bill Wendlingf5e50b62015-03-28 23:38:12 -0700212
Bill Wendlingf09121c2015-10-20 22:59:33 -0700213
Andy Haydena00a6bf2015-06-15 18:47:41 -0700214Example as a module
215===================
216
Andy Hayden4af71682015-06-17 15:42:43 -0700217The two main APIs for calling yapf are ``FormatCode`` and ``FormatFile``, these
218share several arguments which are described below:
Andy Haydena00a6bf2015-06-15 18:47:41 -0700219
220.. code-block:: python
221
Andy Hayden4af71682015-06-17 15:42:43 -0700222 >>> from yapf.yapf_api import FormatCode # reformat a string of code
Ɓukasz Langa94089872015-09-22 16:02:26 -0700223
Andy Haydena00a6bf2015-06-15 18:47:41 -0700224 >>> FormatCode("f ( a = 1, b = 2 )")
225 'f(a=1, b=2)\n'
226
Andy Hayden4af71682015-06-17 15:42:43 -0700227A ``style_config`` argument: Either a style name or a path to a file that contains
Andy Haydena00a6bf2015-06-15 18:47:41 -0700228formatting style settings. If None is specified, use the default style
229as set in ``style.DEFAULT_STYLE_FACTORY``.
230
231.. code-block:: python
232
233 >>> FormatCode("def g():\n return True", style_config='pep8')
234 'def g():\n return True\n'
235
Andy Haydena00a6bf2015-06-15 18:47:41 -0700236A ``lines`` argument: A list of tuples of lines (ints), [start, end],
237that we want to format. The lines are 1-based indexed. It can be used by
238third-party code (e.g., IDEs) when reformatting a snippet of code rather
239than a whole file.
240
241.. code-block:: python
242
243 >>> FormatCode("def g( ):\n a=1\n b = 2\n return a==b", lines=[(1, 1), (2, 3)])
244 'def g():\n a = 1\n b = 2\n return a==b\n'
245
246A ``print_diff`` (bool): Instead of returning the reformatted source, return a
247diff that turns the formatted source into reformatter source.
248
249.. code-block:: python
250
251 >>> print(FormatCode("a==b", filename="foo.py", print_diff=True))
Bill Wendlingb8645ea2015-06-30 22:27:56 -0700252 --- foo.py (original)
253 +++ foo.py (reformatted)
Andy Haydena00a6bf2015-06-15 18:47:41 -0700254 @@ -1 +1 @@
255 -a==b
256 +a == b
257
Andy Hayden4af71682015-06-17 15:42:43 -0700258Note: the ``filename`` argument for ``FormatCode`` is what is inserted into
259the diff, the default is ``<unknown>``.
Andy Haydena00a6bf2015-06-15 18:47:41 -0700260
261``FormatFile`` returns reformatted code from the passed file along with its encoding:
262
263.. code-block:: python
264
Andy Hayden4af71682015-06-17 15:42:43 -0700265 >>> from yapf.yapf_api import FormatFile # reformat a file
266
Andy Haydena00a6bf2015-06-15 18:47:41 -0700267 >>> print(open("foo.py").read()) # contents of file
268 a==b
269
270 >>> FormatFile("foo.py")
Andy Hayden4af71682015-06-17 15:42:43 -0700271 ('a == b\n', 'utf-8')
272
Bill Wendlingcfbb1242015-09-20 12:08:18 -0700273The ``in-place`` argument saves the reformatted code back to the file:
Andy Hayden4af71682015-06-17 15:42:43 -0700274
275.. code-block:: python
276
277 >>> FormatFile("foo.py", in_place=True)
278 (None, 'utf-8')
279
280 >>> print(open("foo.py").read()) # contents of file (now fixed)
281 a == b
282
Andy Haydena00a6bf2015-06-15 18:47:41 -0700283
Bill Wendlingf09121c2015-10-20 22:59:33 -0700284Knobs
285=====
286
287``ALIGN_CLOSING_BRACKET_WITH_VISUAL_INDENT``
288 Align closing bracket with visual indentation.
289
Bill Wendling996c3ee2016-05-25 23:52:24 -0700290``ALLOW_MULTILINE_LAMBDAS``
291 Allow lambdas to be formatted on more than one line.
292
Bill Wendlingf09121c2015-10-20 22:59:33 -0700293``BLANK_LINE_BEFORE_NESTED_CLASS_OR_DEF``
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700294 Insert a blank line before a ``def`` or ``class`` immediately nested within
Bill Wendling996c3ee2016-05-25 23:52:24 -0700295 another ``def`` or ``class``. For example:
Bill Wendlingf09121c2015-10-20 22:59:33 -0700296
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700297 .. code-block:: python
Bill Wendlingf09121c2015-10-20 22:59:33 -0700298
299 class Foo:
300 # <------ this blank line
301 def method():
302 pass
303
Ben Plotnick7e088292016-06-09 18:29:56 -0700304``COALESCE_BRACKETS``
305 Do not split consecutive brackets. Only relevant when
306 ``DEDENT_CLOSING_BRACKETS`` is set. For example:
307
308 .. code-block:: python
309
310 call_func_that_takes_a_dict(
311 {
312 'key1': 'value1',
313 'key2': 'value2',
314 }
315 )
316
317 would reformat to:
318
319 .. code-block:: python
320
321 call_func_that_takes_a_dict({
322 'key1': 'value1',
323 'key2': 'value2',
324 })
325
326
Bill Wendlingf09121c2015-10-20 22:59:33 -0700327``COLUMN_LIMIT``
James Broadheadf4dd8042016-01-07 14:40:19 +0000328 The column limit (or max line-length)
Bill Wendlingf09121c2015-10-20 22:59:33 -0700329
330``CONTINUATION_INDENT_WIDTH``
331 Indent width used for line continuations.
332
333``DEDENT_CLOSING_BRACKETS``
334 Put closing brackets on a separate line, dedented, if the bracketed
335 expression can't fit in a single line. Applies to all kinds of brackets,
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700336 including function definitions and calls. For example:
Bill Wendlingf09121c2015-10-20 22:59:33 -0700337
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700338 .. code-block:: python
Bill Wendlingf09121c2015-10-20 22:59:33 -0700339
340 config = {
341 'key1': 'value1',
342 'key2': 'value2',
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700343 } # <--- this bracket is dedented and on a separate line
Bill Wendlingf09121c2015-10-20 22:59:33 -0700344
345 time_series = self.remote_client.query_entity_counters(
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700346 entity='dev3246.region1',
347 key='dns.query_latency_tcp',
348 transform=Transformation.AVERAGE(window=timedelta(seconds=60)),
349 start_ts=now()-timedelta(days=3),
350 end_ts=now(),
351 ) # <--- this bracket is dedented and on a separate line
Bill Wendlingf09121c2015-10-20 22:59:33 -0700352
Bill Wendling0e9b3212017-01-31 14:41:00 -0800353``EACH_DICT_ENTRY_ON_SEPARATE_LINE``
354 Place each dictionary entry onto its own line.
355
Bill Wendlingf09121c2015-10-20 22:59:33 -0700356``I18N_COMMENT``
357 The regex for an internationalization comment. The presence of this comment
358 stops reformatting of that line, because the comments are required to be
359 next to the string they translate.
360
361``I18N_FUNCTION_CALL``
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700362 The internationalization function call names. The presence of this function
Samuel Dion-Girardeau5ae63492016-09-08 21:01:20 -0400363 stops reformatting on that line, because the string it has cannot be moved
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700364 away from the i18n comment.
Bill Wendlingf09121c2015-10-20 22:59:33 -0700365
366``INDENT_DICTIONARY_VALUE``
367 Indent the dictionary value if it cannot fit on the same line as the
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700368 dictionary key. For example:
Bill Wendlingf09121c2015-10-20 22:59:33 -0700369
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700370 .. code-block:: python
Bill Wendlingf09121c2015-10-20 22:59:33 -0700371
372 config = {
373 'key1':
374 'value1',
375 'key2': value1 +
376 value2,
377 }
378
379``INDENT_WIDTH``
380 The number of columns to use for indentation.
381
382``JOIN_MULTIPLE_LINES``
383 Join short lines into one line. E.g., single line ``if`` statements.
384
Bill Wendling9dc79082016-05-10 00:23:53 -0700385``SPACES_AROUND_POWER_OPERATOR``
386 Set to ``True`` to prefer using spaces around ``**``.
387
Alexander Lenz5fda36a2016-08-26 17:27:57 +0200388``SPACES_AROUND_DEFAULT_OR_NAMED_ASSIGN``
389 Set to ``True`` to prefer spaces around the assignment operator for default
390 or keyword arguments.
391
Bill Wendlingf09121c2015-10-20 22:59:33 -0700392``SPACES_BEFORE_COMMENT``
393 The number of spaces required before a trailing comment.
394
Bill Wendling996c3ee2016-05-25 23:52:24 -0700395``SPACE_BETWEEN_ENDING_COMMA_AND_CLOSING_BRACKET``
396 Insert a space between the ending comma and closing bracket of a list, etc.
397
Bill Wendling982c5b32016-05-24 00:47:44 -0700398``SPLIT_ARGUMENTS_WHEN_COMMA_TERMINATED``
399 Split before arguments if the argument list is terminated by a comma.
400
Bill Wendlingf09121c2015-10-20 22:59:33 -0700401``SPLIT_BEFORE_BITWISE_OPERATOR``
402 Set to ``True`` to prefer splitting before ``&``, ``|`` or ``^`` rather
403 than after.
404
Bill Wendling0e9b3212017-01-31 14:41:00 -0800405``SPLIT_BEFORE_DICT_SET_GENERATOR``
406 Split before a dictionary or set generator (comp_for). For example, note
407 the split before the ``for``:
408
409 .. code-block:: python
410
411 foo = {
412 variable: 'Hello world, have a nice day!'
413 for variable in bar if variable != 42
414 }
415
Bill Wendling996c3ee2016-05-25 23:52:24 -0700416``SPLIT_BEFORE_FIRST_ARGUMENT``
417 If an argument / parameter list is going to be split, then split before the
418 first argument.
419
Bill Wendlingf09121c2015-10-20 22:59:33 -0700420``SPLIT_BEFORE_LOGICAL_OPERATOR``
421 Set to ``True`` to prefer splitting before ``and`` or ``or`` rather than
422 after.
423
424``SPLIT_BEFORE_NAMED_ASSIGNS``
425 Split named assignments onto individual lines.
426
427``SPLIT_PENALTY_AFTER_OPENING_BRACKET``
428 The penalty for splitting right after the opening bracket.
429
430``SPLIT_PENALTY_AFTER_UNARY_OPERATOR``
431 The penalty for splitting the line after a unary operator.
432
Bill Wendling996c3ee2016-05-25 23:52:24 -0700433``SPLIT_PENALTY_BEFORE_IF_EXPR``
434 The penalty for splitting right before an ``if`` expression.
435
Bill Wendlingf09121c2015-10-20 22:59:33 -0700436``SPLIT_PENALTY_BITWISE_OPERATOR``
437 The penalty of splitting the line around the ``&``, ``|``, and ``^``
438 operators.
439
440``SPLIT_PENALTY_EXCESS_CHARACTER``
441 The penalty for characters over the column limit.
442
443``SPLIT_PENALTY_FOR_ADDED_LINE_SPLIT``
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700444 The penalty incurred by adding a line split to the unwrapped line. The more
445 line splits added the higher the penalty.
Bill Wendlingf09121c2015-10-20 22:59:33 -0700446
447``SPLIT_PENALTY_IMPORT_NAMES``
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700448 The penalty of splitting a list of ``import as`` names. For example:
Bill Wendlingf09121c2015-10-20 22:59:33 -0700449
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700450 .. code-block:: python
Bill Wendlingf09121c2015-10-20 22:59:33 -0700451
452 from a_very_long_or_indented_module_name_yada_yad import (long_argument_1,
453 long_argument_2,
454 long_argument_3)
455
456 would reformat to something like:
457
Bill Wendlingc2a9e0d2016-05-24 20:51:04 -0700458 .. code-block:: python
Bill Wendlingf09121c2015-10-20 22:59:33 -0700459
460 from a_very_long_or_indented_module_name_yada_yad import (
461 long_argument_1, long_argument_2, long_argument_3)
462
463``SPLIT_PENALTY_LOGICAL_OPERATOR``
464 The penalty of splitting the line around the ``and`` and ``or`` operators.
465
Draconye582d632016-06-05 11:48:26 +0200466``USE_TABS``
467 Use the Tab character for indentation.
468
Bill Wendling8fb9c482015-03-29 17:32:07 -0700469(Potentially) Frequently Asked Questions
470========================================
471
472Why does YAPF destroy my awesome formatting?
473--------------------------------------------
474
475YAPF tries very hard to get the formatting correct. But for some code, it won't
476be as good as hand-formatting. In particular, large data literals may become
477horribly disfigured under YAPF.
478
Diogo Moitinho de Almeida24458d02015-04-02 17:57:22 -0700479The reason for this is many-fold. But in essence YAPF is simply a tool to help
Bill Wendling8fb9c482015-03-29 17:32:07 -0700480with development. It will format things to coincide with the style guide, but
481that may not equate with readability.
482
483What can be done to alleviate this situation is to indicate regions YAPF should
484ignore when reformatting something:
485
486.. code-block:: python
487
488 # yapf: disable
489 FOO = {
490 # ... some very large, complex data literal.
491 }
492
493 BAR = [
494 # ... another large data literal.
495 ]
496 # yapf: enable
497
498You can also disable formatting for a single literal like this:
499
500.. code-block:: python
501
502 BAZ = {
Scott Sandersoneda4e262015-07-05 21:10:06 -0400503 (1, 2, 3, 4),
504 (5, 6, 7, 8),
505 (9, 10, 11, 12),
Bill Wendling8fb9c482015-03-29 17:32:07 -0700506 } # yapf: disable
507
Ɓukasz Langa94089872015-09-22 16:02:26 -0700508To preserve the nice dedented closing brackets, use the
509``dedent_closing_brackets`` in your style. Note that in this case all
510brackets, including function definitions and calls, are going to use
511that style. This provides consistency across the formatted codebase.
512
Bill Wendling7d623452015-03-18 13:36:07 -0700513Why Not Improve Existing Tools?
Bill Wendling8fb9c482015-03-29 17:32:07 -0700514-------------------------------
Bill Wendling7d623452015-03-18 13:36:07 -0700515
516We wanted to use clang-format's reformatting algorithm. It's very powerful and
517designed to come up with the best formatting possible. Existing tools were
518created with different goals in mind, and would require extensive modifications
519to convert to using clang-format's algorithm.
520
Bill Wendling7d623452015-03-18 13:36:07 -0700521Can I Use YAPF In My Program?
Bill Wendling8fb9c482015-03-29 17:32:07 -0700522-----------------------------
Bill Wendling7d623452015-03-18 13:36:07 -0700523
524Please do! YAPF was designed to be used as a library as well as a command line
525tool. This means that a tool or IDE plugin is free to use YAPF.
526
Bill Wendlingf09121c2015-10-20 22:59:33 -0700527
Bill Wendling7d623452015-03-18 13:36:07 -0700528Gory Details
529============
530
531Algorithm Design
532----------------
533
Eli Benderskyd08130d2015-03-19 05:20:46 -0700534The main data structure in YAPF is the ``UnwrappedLine`` object. It holds a list
535of ``FormatToken``\s, that we would want to place on a single line if there were
536no column limit. An exception being a comment in the middle of an expression
Bill Wendling7d623452015-03-18 13:36:07 -0700537statement will force the line to be formatted on more than one line. The
Eli Benderskyd08130d2015-03-19 05:20:46 -0700538formatter works on one ``UnwrappedLine`` object at a time.
Bill Wendling7d623452015-03-18 13:36:07 -0700539
Eli Benderskyd08130d2015-03-19 05:20:46 -0700540An ``UnwrappedLine`` typically won't affect the formatting of lines before or
541after it. There is a part of the algorithm that may join two or more
542``UnwrappedLine``\s into one line. For instance, an if-then statement with a
Bill Wendlingf5e50b62015-03-28 23:38:12 -0700543short body can be placed on a single line:
544
545.. code-block:: python
Bill Wendling7d623452015-03-18 13:36:07 -0700546
547 if a == 42: continue
548
549YAPF's formatting algorithm creates a weighted tree that acts as the solution
550space for the algorithm. Each node in the tree represents the result of a
551formatting decision --- i.e., whether to split or not to split before a token.
552Each formatting decision has a cost associated with it. Therefore, the cost is
553realized on the edge between two nodes. (In reality, the weighted tree doesn't
554have separate edge objects, so the cost resides on the nodes themselves.)
555
556For example, take the following Python code snippet. For the sake of this
557example, assume that line (1) violates the column limit restriction and needs to
558be reformatted.
559
Bill Wendlingfa22c892015-03-18 13:42:25 -0700560.. code-block:: python
Bill Wendling7d623452015-03-18 13:36:07 -0700561
Bill Wendlingfa22c892015-03-18 13:42:25 -0700562 def xxxxxxxxxxx(aaaaaaaaaaaa, bbbbbbbbb, cccccccc, dddddddd, eeeeee): # 1
563 pass # 2
Bill Wendling7d623452015-03-18 13:36:07 -0700564
565For line (1), the algorithm will build a tree where each node (a
Eli Benderskyd08130d2015-03-19 05:20:46 -0700566``FormattingDecisionState`` object) is the state of the line at that token given
567the decision to split before the token or not. Note: the ``FormatDecisionState``
568objects are copied by value so each node in the graph is unique and a change in
569one doesn't affect other nodes.
Bill Wendling7d623452015-03-18 13:36:07 -0700570
Bill Wendlingfa22c892015-03-18 13:42:25 -0700571Heuristics are used to determine the costs of splitting or not splitting.
572Because a node holds the state of the tree up to a token's insertion, it can
573easily determine if a splitting decision will violate one of the style
Bill Wendling7d623452015-03-18 13:36:07 -0700574requirements. For instance, the heuristic is able to apply an extra penalty to
575the edge when not splitting between the previous token and the one being added.
576
577There are some instances where we will never want to split the line, because
578doing so will always be detrimental (i.e., it will require a backslash-newline,
579which is very rarely desirable). For line (1), we will never want to split the
Eli Benderskyd08130d2015-03-19 05:20:46 -0700580first three tokens: ``def``, ``xxxxxxxxxxx``, and ``(``. Nor will we want to
581split between the ``)`` and the ``:`` at the end. These regions are said to be
582"unbreakable." This is reflected in the tree by there not being a "split"
Bill Wendling7d623452015-03-18 13:36:07 -0700583decision (left hand branch) within the unbreakable region.
584
585Now that we have the tree, we determine what the "best" formatting is by finding
586the path through the tree with the lowest cost.
587
588And that's it!