]> 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:

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