]> git.madduck.net Git - etc/vim.git/blob - docs/the_black_code_style.md

madduck's git repository

Every one of the projects in this repository is available at the canonical URL git://git.madduck.net/madduck/pub/<projectpath> — see each project's metadata for the exact URL.

All patches and comments are welcome. Please squash your changes to logical commits before using git-format-patch and git-send-email to patches@git.madduck.net. If you'd read over the Git project's submission guidelines and adhered to them, I'd be especially grateful.

SSH access, as well as push access can be individually arranged.

If you use my repositories frequently, consider adding the following snippet to ~/.gitconfig and using the third clone URL listed for each project:

[url "git://git.madduck.net/madduck/"]
  insteadOf = madduck:

Elaborate on what AST changes Black might perform
[etc/vim.git] / docs / the_black_code_style.md
1 # The _Black_ code style
2
3 ## Code style
4
5 _Black_ reformats entire files in place. It is not configurable. It doesn't take
6 previous formatting into account. It doesn't reformat blocks that start with
7 `# fmt: off` and end with `# fmt: on`. `# fmt: on/off` have to be on the same level of
8 indentation. It also recognizes [YAPF](https://github.com/google/yapf)'s block comments
9 to the same effect, as a courtesy for straddling code.
10
11 ### How _Black_ wraps lines
12
13 _Black_ ignores previous formatting and applies uniform horizontal and vertical
14 whitespace to your code. The rules for horizontal whitespace can be summarized as: do
15 whatever makes `pycodestyle` happy. The coding style used by _Black_ can be viewed as a
16 strict subset of PEP 8.
17
18 As for vertical whitespace, _Black_ tries to render one full expression or simple
19 statement per line. If this fits the allotted line length, great.
20
21 ```py3
22 # in:
23
24 j = [1,
25      2,
26      3
27 ]
28
29 # out:
30
31 j = [1, 2, 3]
32 ```
33
34 If not, _Black_ will look at the contents of the first outer matching brackets and put
35 that in a separate indented line.
36
37 ```py3
38 # in:
39
40 ImportantClass.important_method(exc, limit, lookup_lines, capture_locals, extra_argument)
41
42 # out:
43
44 ImportantClass.important_method(
45     exc, limit, lookup_lines, capture_locals, extra_argument
46 )
47 ```
48
49 If that still doesn't fit the bill, it will decompose the internal expression further
50 using the same rule, indenting matching brackets every time. If the contents of the
51 matching brackets pair are comma-separated (like an argument list, or a dict literal,
52 and so on) then _Black_ will first try to keep them on the same line with the matching
53 brackets. If that doesn't work, it will put all of them in separate lines.
54
55 ```py3
56 # in:
57
58 def very_important_function(template: str, *variables, file: os.PathLike, engine: str, header: bool = True, debug: bool = False):
59     """Applies `variables` to the `template` and writes to `file`."""
60     with open(file, 'w') as f:
61         ...
62
63 # out:
64
65 def very_important_function(
66     template: str,
67     *variables,
68     file: os.PathLike,
69     engine: str,
70     header: bool = True,
71     debug: bool = False,
72 ):
73     """Applies `variables` to the `template` and writes to `file`."""
74     with open(file, "w") as f:
75         ...
76 ```
77
78 _Black_ prefers parentheses over backslashes, and will remove backslashes if found.
79
80 ```py3
81 # in:
82
83 if some_short_rule1 \
84   and some_short_rule2:
85       ...
86
87 # out:
88
89 if some_short_rule1 and some_short_rule2:
90   ...
91
92
93 # in:
94
95 if some_long_rule1 \
96   and some_long_rule2:
97     ...
98
99 # out:
100
101 if (
102     some_long_rule1
103     and some_long_rule2
104 ):
105     ...
106
107 ```
108
109 Backslashes and multiline strings are one of the two places in the Python grammar that
110 break significant indentation. You never need backslashes, they are used to force the
111 grammar to accept breaks that would otherwise be parse errors. That makes them confusing
112 to look at and brittle to modify. This is why _Black_ always gets rid of them.
113
114 If you're reaching for backslashes, that's a clear signal that you can do better if you
115 slightly refactor your code. I hope some of the examples above show you that there are
116 many ways in which you can do it.
117
118 However there is one exception: `with` statements using multiple context managers.
119 Python's grammar does not allow organizing parentheses around the series of context
120 managers.
121
122 We don't want formatting like:
123
124 ```py3
125 with make_context_manager1() as cm1, make_context_manager2() as cm2, make_context_manager3() as cm3, make_context_manager4() as cm4:
126     ...  # nothing to split on - line too long
127 ```
128
129 So _Black_ will now format it like this:
130
131 ```py3
132 with \
133      make_context_manager(1) as cm1, \
134      make_context_manager(2) as cm2, \
135      make_context_manager(3) as cm3, \
136      make_context_manager(4) as cm4 \
137 :
138     ...  # backslashes and an ugly stranded colon
139 ```
140
141 You might have noticed that closing brackets are always dedented and that a trailing
142 comma is always added. Such formatting produces smaller diffs; when you add or remove an
143 element, it's always just one line. Also, having the closing bracket dedented provides a
144 clear delimiter between two distinct sections of the code that otherwise share the same
145 indentation level (like the arguments list and the docstring in the example above).
146
147 If a data structure literal (tuple, list, set, dict) or a line of "from" imports cannot
148 fit in the allotted length, it's always split into one element per line. This minimizes
149 diffs as well as enables readers of code to find which commit introduced a particular
150 entry. This also makes _Black_ compatible with [isort](https://pypi.org/p/isort/) with
151 the following configuration.
152
153 <details>
154 <summary>A compatible `.isort.cfg`</summary>
155
156 ```cfg
157 [settings]
158 multi_line_output = 3
159 include_trailing_comma = True
160 force_grid_wrap = 0
161 use_parentheses = True
162 ensure_newline_before_comments = True
163 line_length = 88
164 ```
165
166 The equivalent command line is:
167
168 ```
169 $ isort --multi-line=3 --trailing-comma --force-grid-wrap=0 --use-parentheses --line-width=88 [ file.py ]
170 ```
171
172 </details>
173
174 ### Line length
175
176 You probably noticed the peculiar default line length. _Black_ defaults to 88 characters
177 per line, which happens to be 10% over 80. This number was found to produce
178 significantly shorter files than sticking with 80 (the most popular), or even 79 (used
179 by the standard library). In general,
180 [90-ish seems like the wise choice](https://youtu.be/wf-BqAjZb8M?t=260).
181
182 If you're paid by the line of code you write, you can pass `--line-length` with a lower
183 number. _Black_ will try to respect that. However, sometimes it won't be able to without
184 breaking other rules. In those rare cases, auto-formatted code will exceed your allotted
185 limit.
186
187 You can also increase it, but remember that people with sight disabilities find it
188 harder to work with line lengths exceeding 100 characters. It also adversely affects
189 side-by-side diff review on typical screen resolutions. Long lines also make it harder
190 to present code neatly in documentation or talk slides.
191
192 If you're using Flake8, you can bump `max-line-length` to 88 and mostly forget about it.
193 However, it's better if you use [Bugbear](https://github.com/PyCQA/flake8-bugbear)'s
194 B950 warning instead of E501, and bump the max line length to 88 (or the `--line-length`
195 you used for black), which will align more with black's _"try to respect
196 `--line-length`, but don't become crazy if you can't"_. You'd do it like this:
197
198 ```ini
199 [flake8]
200 max-line-length = 88
201 ...
202 select = C,E,F,W,B,B950
203 extend-ignore = E203, E501
204 ```
205
206 Explanation of why E203 is disabled can be found further in this documentation. And if
207 you're curious about the reasoning behind B950,
208 [Bugbear's documentation](https://github.com/PyCQA/flake8-bugbear#opinionated-warnings)
209 explains it. The tl;dr is "it's like highway speed limits, we won't bother you if you
210 overdo it by a few km/h".
211
212 **If you're looking for a minimal, black-compatible flake8 configuration:**
213
214 ```ini
215 [flake8]
216 max-line-length = 88
217 extend-ignore = E203
218 ```
219
220 ### Empty lines
221
222 _Black_ avoids spurious vertical whitespace. This is in the spirit of PEP 8 which says
223 that in-function vertical whitespace should only be used sparingly.
224
225 _Black_ will allow single empty lines inside functions, and single and double empty
226 lines on module level left by the original editors, except when they're within
227 parenthesized expressions. Since such expressions are always reformatted to fit minimal
228 space, this whitespace is lost.
229
230 It will also insert proper spacing before and after function definitions. It's one line
231 before and after inner functions and two lines before and after module-level functions
232 and classes. _Black_ will not put empty lines between function/class definitions and
233 standalone comments that immediately precede the given function/class.
234
235 _Black_ will enforce single empty lines between a class-level docstring and the first
236 following field or method. This conforms to
237 [PEP 257](https://www.python.org/dev/peps/pep-0257/#multi-line-docstrings).
238
239 _Black_ won't insert empty lines after function docstrings unless that empty line is
240 required due to an inner function starting immediately after.
241
242 ### Trailing commas
243
244 _Black_ will add trailing commas to expressions that are split by comma where each
245 element is on its own line. This includes function signatures.
246
247 One exception to adding trailing commas is function signatures containing `*`, `*args`,
248 or `**kwargs`. In this case a trailing comma is only safe to use on Python 3.6. _Black_
249 will detect if your file is already 3.6+ only and use trailing commas in this situation.
250 If you wonder how it knows, it looks for f-strings and existing use of trailing commas
251 in function signatures that have stars in them. In other words, if you'd like a trailing
252 comma in this situation and _Black_ didn't recognize it was safe to do so, put it there
253 manually and _Black_ will keep it.
254
255 A pre-existing trailing comma informs _Black_ to always explode contents of the current
256 bracket pair into one item per line. Read more about this in the
257 [Pragmatism](#pragmatism) section below.
258
259 ### Strings
260
261 _Black_ prefers double quotes (`"` and `"""`) over single quotes (`'` and `'''`). It
262 will replace the latter with the former as long as it does not result in more backslash
263 escapes than before.
264
265 _Black_ also standardizes string prefixes, making them always lowercase. On top of that,
266 if your code is already Python 3.6+ only or it's using the `unicode_literals` future
267 import, _Black_ will remove `u` from the string prefix as it is meaningless in those
268 scenarios.
269
270 The main reason to standardize on a single form of quotes is aesthetics. Having one kind
271 of quotes everywhere reduces reader distraction. It will also enable a future version of
272 _Black_ to merge consecutive string literals that ended up on the same line (see
273 [#26](https://github.com/psf/black/issues/26) for details).
274
275 Why settle on double quotes? They anticipate apostrophes in English text. They match the
276 docstring standard described in
277 [PEP 257](https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring). An empty
278 string in double quotes (`""`) is impossible to confuse with a one double-quote
279 regardless of fonts and syntax highlighting used. On top of this, double quotes for
280 strings are consistent with C which Python interacts a lot with.
281
282 On certain keyboard layouts like US English, typing single quotes is a bit easier than
283 double quotes. The latter requires use of the Shift key. My recommendation here is to
284 keep using whatever is faster to type and let _Black_ handle the transformation.
285
286 If you are adopting _Black_ in a large project with pre-existing string conventions
287 (like the popular
288 ["single quotes for data, double quotes for human-readable strings"](https://stackoverflow.com/a/56190)),
289 you can pass `--skip-string-normalization` on the command line. This is meant as an
290 adoption helper, avoid using this for new projects.
291
292 As an experimental option, _Black_ splits long strings (using parentheses where
293 appropriate) and merges short ones. When split, parts of f-strings that don't need
294 formatting are converted to plain strings. User-made splits are respected when they do
295 not exceed the line length limit. Line continuation backslashes are converted into
296 parenthesized strings. Unnecessary parentheses are stripped. To enable experimental
297 string processing, pass `--experimental-string-processing` on the command line. Because
298 the functionality is experimental, feedback and issue reports are highly encouraged!
299
300 _Black_ also processes docstrings. Firstly the indentation of docstrings is corrected
301 for both quotations and the text within, although relative indentation in the text is
302 preserved. Superfluous trailing whitespace on each line and unnecessary new lines at the
303 end of the docstring are removed. All leading tabs are converted to spaces, but tabs
304 inside text are preserved. Whitespace leading and trailing one-line docstrings is
305 removed. The quotations of an empty docstring are separated with one space.
306
307 ### Numeric literals
308
309 _Black_ standardizes most numeric literals to use lowercase letters for the syntactic
310 parts and uppercase letters for the digits themselves: `0xAB` instead of `0XAB` and
311 `1e10` instead of `1E10`. Python 2 long literals are styled as `2L` instead of `2l` to
312 avoid confusion between `l` and `1`.
313
314 ### Line breaks & binary operators
315
316 _Black_ will break a line before a binary operator when splitting a block of code over
317 multiple lines. This is so that _Black_ is compliant with the recent changes in the
318 [PEP 8](https://www.python.org/dev/peps/pep-0008/#should-a-line-break-before-or-after-a-binary-operator)
319 style guide, which emphasizes that this approach improves readability.
320
321 ### Slices
322
323 PEP 8
324 [recommends](https://www.python.org/dev/peps/pep-0008/#whitespace-in-expressions-and-statements)
325 to treat `:` in slices as a binary operator with the lowest priority, and to leave an
326 equal amount of space on either side, except if a parameter is omitted (e.g.
327 `ham[1 + 1 :]`). It recommends no spaces around `:` operators for "simple expressions"
328 (`ham[lower:upper]`), and extra space for "complex expressions"
329 (`ham[lower : upper + offset]`). _Black_ treats anything more than variable names as
330 "complex" (`ham[lower : upper + 1]`). It also states that for extended slices, both `:`
331 operators have to have the same amount of spacing, except if a parameter is omitted
332 (`ham[1 + 1 ::]`). _Black_ enforces these rules consistently.
333
334 This behaviour may raise `E203 whitespace before ':'` warnings in style guide
335 enforcement tools like Flake8. Since `E203` is not PEP 8 compliant, you should tell
336 Flake8 to ignore these warnings.
337
338 ### Parentheses
339
340 Some parentheses are optional in the Python grammar. Any expression can be wrapped in a
341 pair of parentheses to form an atom. There are a few interesting cases:
342
343 - `if (...):`
344 - `while (...):`
345 - `for (...) in (...):`
346 - `assert (...), (...)`
347 - `from X import (...)`
348 - assignments like:
349   - `target = (...)`
350   - `target: type = (...)`
351   - `some, *un, packing = (...)`
352   - `augmented += (...)`
353
354 In those cases, parentheses are removed when the entire statement fits in one line, or
355 if the inner expression doesn't have any delimiters to further split on. If there is
356 only a single delimiter and the expression starts or ends with a bracket, the
357 parenthesis can also be successfully omitted since the existing bracket pair will
358 organize the expression neatly anyway. Otherwise, the parentheses are added.
359
360 Please note that _Black_ does not add or remove any additional nested parentheses that
361 you might want to have for clarity or further code organization. For example those
362 parentheses are not going to be removed:
363
364 ```py3
365 return not (this or that)
366 decision = (maybe.this() and values > 0) or (maybe.that() and values < 0)
367 ```
368
369 ### Call chains
370
371 Some popular APIs, like ORMs, use call chaining. This API style is known as a
372 [fluent interface](https://en.wikipedia.org/wiki/Fluent_interface). _Black_ formats
373 those by treating dots that follow a call or an indexing operation like a very low
374 priority delimiter. It's easier to show the behavior than to explain it. Look at the
375 example:
376
377 ```py3
378 def example(session):
379     result = (
380         session.query(models.Customer.id)
381         .filter(
382             models.Customer.account_id == account_id,
383             models.Customer.email == email_address,
384         )
385         .order_by(models.Customer.id.asc())
386         .all()
387     )
388 ```
389
390 ### Typing stub files
391
392 PEP 484 describes the syntax for type hints in Python. One of the use cases for typing
393 is providing type annotations for modules which cannot contain them directly (they might
394 be written in C, or they might be third-party, or their implementation may be overly
395 dynamic, and so on).
396
397 To solve this,
398 [stub files with the `.pyi` file extension](https://www.python.org/dev/peps/pep-0484/#stub-files)
399 can be used to describe typing information for an external module. Those stub files omit
400 the implementation of classes and functions they describe, instead they only contain the
401 structure of the file (listing globals, functions, and classes with their members). The
402 recommended code style for those files is more terse than PEP 8:
403
404 - prefer `...` on the same line as the class/function signature;
405 - avoid vertical whitespace between consecutive module-level functions, names, or
406   methods and fields within a single class;
407 - use a single blank line between top-level class definitions, or none if the classes
408   are very small.
409
410 _Black_ enforces the above rules. There are additional guidelines for formatting `.pyi`
411 file that are not enforced yet but might be in a future version of the formatter:
412
413 - all function bodies should be empty (contain `...` instead of the body);
414 - do not use docstrings;
415 - prefer `...` over `pass`;
416 - for arguments with a default, use `...` instead of the actual default;
417 - avoid using string literals in type annotations, stub files support forward references
418   natively (like Python 3.7 code with `from __future__ import annotations`);
419 - use variable annotations instead of type comments, even for stubs that target older
420   versions of Python;
421 - for arguments that default to `None`, use `Optional[]` explicitly;
422 - use `float` instead of `Union[int, float]`.
423
424 ## Pragmatism
425
426 Early versions of _Black_ used to be absolutist in some respects. They took after its
427 initial author. This was fine at the time as it made the implementation simpler and
428 there were not many users anyway. Not many edge cases were reported. As a mature tool,
429 _Black_ does make some exceptions to rules it otherwise holds. This section documents
430 what those exceptions are and why this is the case.
431
432 ### The magic trailing comma
433
434 _Black_ in general does not take existing formatting into account.
435
436 However, there are cases where you put a short collection or function call in your code
437 but you anticipate it will grow in the future.
438
439 For example:
440
441 ```py3
442 TRANSLATIONS = {
443     "en_us": "English (US)",
444     "pl_pl": "polski",
445 }
446 ```
447
448 Early versions of _Black_ used to ruthlessly collapse those into one line (it fits!).
449 Now, you can communicate that you don't want that by putting a trailing comma in the
450 collection yourself. When you do, _Black_ will know to always explode your collection
451 into one item per line.
452
453 How do you make it stop? Just delete that trailing comma and _Black_ will collapse your
454 collection into one line if it fits.
455
456 If you must, you can recover the behaviour of early versions of Black with the option
457 `--skip-magic-trailing-comma` / `-C`.
458
459 ### r"strings" and R"strings"
460
461 _Black_ normalizes string quotes as well as string prefixes, making them lowercase. One
462 exception to this rule is r-strings. It turns out that the very popular
463 [MagicPython](https://github.com/MagicStack/MagicPython/) syntax highlighter, used by
464 default by (among others) GitHub and Visual Studio Code, differentiates between
465 r-strings and R-strings. The former are syntax highlighted as regular expressions while
466 the latter are treated as true raw strings with no special semantics.
467
468 ### AST before and after formatting
469
470 When run with `--safe`, _Black_ checks that the code before and after is semantically
471 equivalent. This check is done by comparing the AST of the source with the AST of the
472 target. There are three limited cases in which the AST does differ:
473
474 1. _Black_ cleans up leading and trailing whitespace of docstrings, re-indenting them if
475    needed. It's been one of the most popular user-reported features for the formatter to
476    fix whitespace issues with docstrings. While the result is technically an AST
477    difference, due to the various possibilities of forming docstrings, all realtime use
478    of docstrings that we're aware of sanitizes indentation and leading/trailing
479    whitespace anyway.
480
481 2. _Black_ manages optional parentheses for some statements. In the case of the `del`
482    statement, presence of wrapping parentheses or lack of thereof changes the resulting
483    AST but is semantically equivalent in the interpreter.
484
485 3. _Black_ might move comments around, which includes type comments. Those are part of
486    the AST as of Python 3.8. While the tool implements a number of special cases for
487    those comments, there is no guarantee they will remain where they were in the source.
488    Note that this doesn't change runtime behavior of the source code.
489
490 To put things in perspective, the code equivalence check is a feature of _Black_ which
491 other formatters don't implement at all. It is of crucial importance to us to ensure
492 code behaves the way it did before it got reformatted. We treat this as a feature and
493 there are no plans to relax this in the future. The exceptions enumerated above stem
494 from either user feedback or implementation details of the tool. In each case we made
495 due diligence to ensure that the AST divergence is of no practical consequence.