Debian Codegraph @

docs/the_black_code_style/current_style.md

raw
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_ follows PEP 8 in spirit and enforces a consistent subset of its
10 formatting recommendations. It does not implement every style rule covered by PEP 8.
11
12 This document describes the current formatting style. If you're interested in trying out
13 where the style is heading, see [future style](./future_style.md) and try running
14 `black --preview`.
15
16 ### How _Black_ wraps lines
17
18 _Black_ ignores previous formatting and applies uniform horizontal and vertical
19 whitespace to your code. The rules for horizontal whitespace can be summarized as: do
20 whatever makes `pycodestyle` happy.
21
22 As for vertical whitespace, _Black_ tries to render one full expression or simple
23 statement per line. If this fits the allotted line length, great.
24
25 ```python
26 # in:
27
28 j = [1,
29 2,
30 3
31 ]
32
33 # out:
34
35 j = [1, 2, 3]
36 ```
37
38 If not, _Black_ will look at the contents of the first outer matching brackets and put
39 that in a separate indented line.
40
41 ```python
42 # in:
43
44 ImportantClass.important_method(exc, limit, lookup_lines, capture_locals, extra_argument)
45
46 # out:
47
48 ImportantClass.important_method(
49 exc, limit, lookup_lines, capture_locals, extra_argument
50 )
51 ```
52
53 If that still doesn't fit the bill, it will decompose the internal expression further
54 using the same rule, indenting matching brackets every time. If the contents of the
55 matching brackets pair are comma-separated (like an argument list, or a dict literal,
56 and so on) then _Black_ will first try to keep them on the same line with the matching
57 brackets. If that doesn't work, it will put all of them in separate lines.
58
59 ```python
60 # in:
61
62 def very_important_function(template: str, *variables, file: os.PathLike, engine: str, header: bool = True, debug: bool = False):
63 """Applies `variables` to the `template` and writes to `file`."""
64 with open(file, 'w') as f:
65 ...
66
67 # out:
68
69 def very_important_function(
70 template: str,
71 *variables,
72 file: os.PathLike,
73 engine: str,
74 header: bool = True,
75 debug: bool = False,
76 ):
77 """Applies `variables` to the `template` and writes to `file`."""
78 with open(file, "w") as f:
79 ...
80 ```
81
82 If a data structure literal (tuple, list, set, dict) or a line of "from" imports cannot
83 fit in the allotted length, it's always split into one element per line. This minimizes
84 diffs as well as enables readers of code to find which commit introduced a particular
85 entry. This also makes _Black_ compatible with
86 [isort](../guides/using_black_with_other_tools.md#isort) with the ready-made `black`
87 profile or manual configuration.
88
89 You might have noticed that closing brackets are always dedented and that a trailing
90 comma is always added. Such formatting produces smaller diffs; when you add or remove an
91 element, it's always just one line. Also, having the closing bracket dedented provides a
92 clear delimiter between two distinct sections of the code that otherwise share the same
93 indentation level (like the arguments list and the docstring in the example above).
94
95 (labels/why-no-backslashes)=
96
97 _Black_ prefers parentheses over backslashes, and will remove backslashes if found.
98
99 ```python
100 # in:
101
102 if some_short_rule1 \
103 and some_short_rule2:
104 ...
105
106 # out:
107
108 if some_short_rule1 and some_short_rule2:
109 ...
110
111
112 # in:
113
114 if some_long_rule1 \
115 and some_long_rule2:
116 ...
117
118 # out:
119
120 if (
121 some_long_rule1
122 and some_long_rule2
123 ):
124 ...
125
126 ```
127
128 Backslashes and multiline strings are one of the two places in the Python grammar that
129 break significant indentation. You never need backslashes, they are used to force the
130 grammar to accept breaks that would otherwise be parse errors. That makes them confusing
131 to look at and brittle to modify. This is why _Black_ always gets rid of them.
132
133 If you're reaching for backslashes, that's a clear signal that you can do better if you
134 slightly refactor your code. I hope some of the examples above show you that there are
135 many ways in which you can do it.
136
137 (labels/line-length)=
138
139 ### Line length
140
141 You probably noticed the peculiar default line length. _Black_ defaults to 88 characters
142 per line, which happens to be 10% over 80. This number was found to produce
143 significantly shorter files than sticking with 80 (the most popular), or even 79 (used
144 by the standard library). In general,
145 [90-ish seems like the wise choice](https://youtu.be/wf-BqAjZb8M?t=260).
146
147 If you're paid by the lines of code you write, you can pass `--line-length` with a lower
148 number. _Black_ will try to respect that. However, sometimes it won't be able to without
149 breaking other rules. In those rare cases, auto-formatted code will exceed your allotted
150 limit.
151
152 You can also increase it, but remember that people with sight disabilities find it
153 harder to work with line lengths exceeding 100 characters. It also adversely affects
154 side-by-side diff review on typical screen resolutions. Long lines also make it harder
155 to present code neatly in documentation or talk slides.
156
157 #### Flake8 and other linters
158
159 See [Using _Black_ with other tools](../guides/using_black_with_other_tools.md) about
160 linter compatibility.
161
162 ### Empty lines
163
164 _Black_ avoids spurious vertical whitespace. This is in the spirit of PEP 8 which says
165 that in-function vertical whitespace should only be used sparingly.
166
167 _Black_ will allow single empty lines inside functions, and single and double empty
168 lines on module level left by the original editors, except when they're within
169 parenthesized expressions. Since such expressions are always reformatted to fit minimal
170 space, this whitespace is lost.
171
172 ```python
173 # in:
174
175 def function(
176 some_argument: int,
177
178 other_argument: int = 5,
179 ) -> EmptyLineInParenWillBeDeleted:
180
181
182
183 print("One empty line above me will be kept!")
184
185 def this_is_okay_too():
186 print("No empty line here")
187 # out:
188
189 def function(
190 some_argument: int,
191 other_argument: int = 5,
192 ) -> EmptyLineInParenWillBeDeleted:
193
194 print("One empty line above me will be kept!")
195
196
197 def this_is_okay_too():
198 print("No empty line here")
199 ```
200
201 It will also insert proper spacing before and after function definitions. It's one line
202 before and after inner functions and two lines before and after module-level functions
203 and classes. _Black_ will not put empty lines between function/class definitions and
204 standalone comments that immediately precede the given function/class.
205
206 _Black_ will enforce single empty lines between a class-level docstring and the first
207 following field or method. This conforms to
208 [PEP 257](https://peps.python.org/pep-0257/#multi-line-docstrings).
209
210 _Black_ won't insert empty lines after function docstrings unless that empty line is
211 required due to an inner function starting immediately after.
212
213 ### Comments
214
215 _Black_ does not format comment contents, but it enforces two spaces between code and a
216 comment on the same line, and a space before the comment text begins. Some types of
217 comments that require specific spacing rules are respected: shebangs (`#! comment`), doc
218 comments (`#: comment`), section comments with long runs of hashes, and Spyder cells.
219 Non-breaking spaces after hashes are also preserved. Comments may sometimes be moved
220 because of formatting changes, which can break tools that assign special meaning to
221 them. See [AST before and after formatting](#ast-before-and-after-formatting) for more
222 discussion.
223
224 ### Trailing commas
225
226 _Black_ will add trailing commas to expressions that are split by comma where each
227 element is on its own line. This includes function signatures.
228
229 One exception to adding trailing commas is function signatures containing `*`, `*args`,
230 or `**kwargs`. In this case a trailing comma is only safe to use on Python 3.6. _Black_
231 will detect if your file is already 3.6+ only and use trailing commas in this situation.
232 If you wonder how it knows, it looks for f-strings and existing use of trailing commas
233 in function signatures that have stars in them. In other words, if you'd like a trailing
234 comma in this situation and _Black_ didn't recognize it was safe to do so, put it there
235 manually and _Black_ will keep it.
236
237 A pre-existing trailing comma informs _Black_ to always explode contents of the current
238 bracket pair into one item per line. Read more about this in the
239 [Pragmatism](#pragmatism) section below.
240
241 (labels/strings)=
242
243 ### Strings
244
245 _Black_ prefers double quotes (`"` and `"""`) over single quotes (`'` and `'''`). It
246 will replace the latter with the former as long as it does not result in more backslash
247 escapes than before.
248
249 _Black_ also standardizes string prefixes. Prefix characters are made lowercase with the
250 exception of [capital "R" prefixes](#rstrings-and-rstrings), unicode literal markers
251 (`u`) are removed because they are meaningless in Python 3, and in the case of multiple
252 characters "r" is put first as in spoken language: "raw f-string".
253
254 Another area where Python allows multiple ways to format a string is escape sequences.
255 For example, `"\uabcd"` and `"\uABCD"` evaluate to the same string. _Black_ normalizes
256 such escape sequences to lowercase, but uses uppercase for `\N` named character escapes,
257 such as `"\N{MEETEI MAYEK LETTER HUK}"`.
258
259 The main reason to standardize on a single form of quotes is aesthetics. Having one kind
260 of quotes everywhere reduces reader distraction. It will also enable a future version of
261 _Black_ to merge consecutive string literals that ended up on the same line (see
262 [#26](https://github.com/psf/black/issues/26) for details).
263
264 Why settle on double quotes? They anticipate apostrophes in English text. They match the
265 docstring standard described in
266 [PEP 257](https://peps.python.org/pep-0257/#what-is-a-docstring). An empty string in
267 double quotes (`""`) is impossible to confuse with a one double-quote regardless of
268 fonts and syntax highlighting used. On top of this, double quotes for strings are
269 consistent with C which Python interacts a lot with.
270
271 On certain keyboard layouts like US English, typing single quotes is a bit easier than
272 double quotes. The latter requires use of the Shift key. My recommendation here is to
273 keep using whatever is faster to type and let _Black_ handle the transformation.
274
275 If you are adopting _Black_ in a large project with pre-existing string conventions
276 (like the popular
277 ["single quotes for data, double quotes for human-readable strings"](https://stackoverflow.com/a/56190)),
278 you can pass `--skip-string-normalization` on the command line. This is meant as an
279 adoption helper, avoid using this for new projects.
280
281 _Black_ also processes docstrings. Firstly the indentation of docstrings is corrected
282 for both quotations and the text within, although relative indentation in the text is
283 preserved. Superfluous trailing whitespace on each line and unnecessary new lines at the
284 end of the docstring are removed. All leading tabs are converted to spaces, but tabs
285 inside text are preserved. Whitespace leading and trailing one-line docstrings is
286 removed.
287
288 ### Numeric literals
289
290 _Black_ standardizes most numeric literals to use lowercase letters for the syntactic
291 parts and uppercase letters for the digits themselves: `0xAB` instead of `0XAB` and
292 `1e10` instead of `1E10`.
293
294 ### Line breaks & binary operators
295
296 _Black_ will break a line before a binary operator when splitting a block of code over
297 multiple lines. This is so that _Black_ is compliant with the recent changes in the
298 [PEP 8](https://peps.python.org/pep-0008/#should-a-line-break-before-or-after-a-binary-operator)
299 style guide, which emphasizes that this approach improves readability.
300
301 Almost all operators will be surrounded by single spaces, the only exceptions are unary
302 operators (`+`, `-`, and `~`), and power operators when both operands are simple. For
303 powers, an operand is considered simple if it's only a NAME, numeric CONSTANT, or
304 attribute access (chained attribute access is allowed), with or without a preceding
305 unary operator.
306
307 ```python
308 # For example, these won't be surrounded by whitespace
309 a = x**y
310 b = config.base**5.2
311 c = config.base**runtime.config.exponent
312 d = 2**5
313 e = 2**~5
314
315 # ... but these will be surrounded by whitespace
316 f = 2 ** get_exponent()
317 g = get_x() ** get_y()
318 h = config['base'] ** 2
319 ```
320
321 ### Slices
322
323 PEP 8
324 [recommends](https://peps.python.org/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 parentheses 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 ```python
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 ```python
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://peps.python.org/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 - prefer `...` over `pass`;
414 - avoid using string literals in type annotations, stub files support forward references
415 natively (like Python 3.7 code with `from __future__ import annotations`);
416 - use variable annotations instead of type comments, even for stubs that target older
417 versions of Python.
418
419 ### Line endings
420
421 _Black_ will normalize line endings (`\n` or `\r\n`) based on the first line ending of
422 the file.
423
424 ### Form feed characters
425
426 _Black_ will retain form feed characters on otherwise empty lines at the module level.
427 Only one form feed is retained for a group of consecutive empty lines. Where there are
428 two empty lines in a row, the form feed is placed on the second line.
429
430 ## Pragmatism
431
432 Early versions of _Black_ used to be absolutist in some respects. They took after its
433 initial author. This was fine at the time as it made the implementation simpler and
434 there were not many users anyway. Not many edge cases were reported. As a mature tool,
435 _Black_ does make some exceptions to rules it otherwise holds. This section documents
436 what those exceptions are and why this is the case.
437
438 (labels/magic-trailing-comma)=
439
440 ### The magic trailing comma
441
442 _Black_ in general does not take existing formatting into account.
443
444 However, there are cases where you put a short collection or function call in your code
445 but you anticipate it will grow in the future.
446
447 For example:
448
449 ```python
450 TRANSLATIONS = {
451 "en_us": "English (US)",
452 "pl_pl": "polski",
453 }
454 ```
455
456 Early versions of _Black_ used to ruthlessly collapse those into one line (it fits!).
457 Now, you can communicate that you don't want that by putting a trailing comma in the
458 collection yourself. When you do, _Black_ will know to always explode your collection
459 into one item per line.
460
461 How do you make it stop? Just delete that trailing comma and _Black_ will collapse your
462 collection into one line if it fits.
463
464 If you must, you can recover the behaviour of early versions of _Black_ with the option
465 `--skip-magic-trailing-comma` / `-C`.
466
467 ### r"strings" and R"strings"
468
469 _Black_ normalizes string quotes as well as string prefixes, making them lowercase. One
470 exception to this rule is r-strings. It turns out that the very popular
471 [MagicPython](https://github.com/MagicStack/MagicPython/) syntax highlighter, used by
472 default by (among others) GitHub and Visual Studio Code, differentiates between
473 r-strings and R-strings. The former are syntax highlighted as regular expressions while
474 the latter are treated as true raw strings with no special semantics.
475
476 (labels/ast-changes)=
477
478 ### AST before and after formatting
479
480 When run with `--safe` (the default), _Black_ checks that the code before and after is
481 semantically equivalent. This check is done by comparing the AST of the source with the
482 AST of the target. There are three limited cases in which the AST does differ:
483
484 1. _Black_ cleans up leading and trailing whitespace of docstrings, re-indenting them if
485 needed. It's been one of the most popular user-reported features for the formatter to
486 fix whitespace issues with docstrings. While the result is technically an AST
487 difference, due to the various possibilities of forming docstrings, all real-world
488 uses of docstrings that we're aware of sanitize indentation and leading/trailing
489 whitespace anyway.
490
491 1. _Black_ manages optional parentheses for some statements. In the case of the `del`
492 statement, presence of wrapping parentheses or lack thereof changes the resulting AST
493 but is semantically equivalent in the interpreter.
494
495 1. _Black_ might move comments around, which includes type comments. Those are part of
496 the AST as of Python 3.8. While the tool implements a number of special cases for
497 those comments, there is no guarantee they will remain where they were in the source.
498 Note that this doesn't change runtime behavior of the source code.
499
500 To put things in perspective, the code equivalence check is a feature of _Black_ which
501 other formatters don't implement at all. It is of crucial importance to us to ensure
502 code behaves the way it did before it got reformatted. We treat this as a feature and
503 there are no plans to relax this in the future. The exceptions enumerated above stem
504 from either user feedback or implementation details of the tool. In each case we made
505 due diligence to ensure that the AST divergence is of no practical consequence.