]> git.madduck.net Git - etc/vim.git/blob - .vim/bundle/black/docs/the_black_code_style/current_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:

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