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.
1 # The _Black_ code style
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.
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.
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`.
22 ### How _Black_ wraps lines
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.
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.
44 If not, _Black_ will look at the contents of the first outer matching brackets and put
45 that in a separate indented line.
50 ImportantClass.important_method(exc, limit, lookup_lines, capture_locals, extra_argument)
54 ImportantClass.important_method(
55 exc, limit, lookup_lines, capture_locals, extra_argument
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.
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:
75 def very_important_function(
83 """Applies `variables` to the `template` and writes to `file`."""
84 with open(file, "w") as f:
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.
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).
101 (labels/why-no-backslashes)=
103 _Black_ prefers parentheses over backslashes, and will remove backslashes if found.
108 if some_short_rule1 \
109 and some_short_rule2:
114 if some_short_rule1 and some_short_rule2:
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.
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.
145 You probably noticed the peculiar default line length. _Black_ defaults to 88 characters
146 per line, which happens to be 10% over 80. This number was found to produce
147 significantly shorter files than sticking with 80 (the most popular), or even 79 (used
148 by the standard library). In general,
149 [90-ish seems like the wise choice](https://youtu.be/wf-BqAjZb8M?t=260).
151 If you're paid by the line of code you write, you can pass `--line-length` with a lower
152 number. _Black_ will try to respect that. However, sometimes it won't be able to without
153 breaking other rules. In those rare cases, auto-formatted code will exceed your allotted
156 You can also increase it, but remember that people with sight disabilities find it
157 harder to work with line lengths exceeding 100 characters. It also adversely affects
158 side-by-side diff review on typical screen resolutions. Long lines also make it harder
159 to present code neatly in documentation or talk slides.
161 If you're using Flake8, you can bump `max-line-length` to 88 and mostly forget about it.
162 However, it's better if you use [Bugbear](https://github.com/PyCQA/flake8-bugbear)'s
163 B950 warning instead of E501, and bump the max line length to 88 (or the `--line-length`
164 you used for black), which will align more with black's _"try to respect
165 `--line-length`, but don't become crazy if you can't"_. You'd do it like this:
171 select = C,E,F,W,B,B950
172 extend-ignore = E203, E501
175 Explanation of why E203 is disabled can be found further in this documentation. And if
176 you're curious about the reasoning behind B950,
177 [Bugbear's documentation](https://github.com/PyCQA/flake8-bugbear#opinionated-warnings)
178 explains it. The tl;dr is "it's like highway speed limits, we won't bother you if you
179 overdo it by a few km/h".
181 **If you're looking for a minimal, black-compatible flake8 configuration:**
191 _Black_ avoids spurious vertical whitespace. This is in the spirit of PEP 8 which says
192 that in-function vertical whitespace should only be used sparingly.
194 _Black_ will allow single empty lines inside functions, and single and double empty
195 lines on module level left by the original editors, except when they're within
196 parenthesized expressions. Since such expressions are always reformatted to fit minimal
197 space, this whitespace is lost.
199 It will also insert proper spacing before and after function definitions. It's one line
200 before and after inner functions and two lines before and after module-level functions
201 and classes. _Black_ will not put empty lines between function/class definitions and
202 standalone comments that immediately precede the given function/class.
204 _Black_ will enforce single empty lines between a class-level docstring and the first
205 following field or method. This conforms to
206 [PEP 257](https://www.python.org/dev/peps/pep-0257/#multi-line-docstrings).
208 _Black_ won't insert empty lines after function docstrings unless that empty line is
209 required due to an inner function starting immediately after.
213 _Black_ does not format comment contents, but it enforces two spaces between code and a
214 comment on the same line, and a space before the comment text begins. Some types of
215 comments that require specific spacing rules are respected: doc comments (`#: comment`),
216 section comments with long runs of hashes, and Spyder cells. Non-breaking spaces after
217 hashes are also preserved. Comments may sometimes be moved because of formatting
218 changes, which can break tools that assign special meaning to them. See
219 [AST before and after formatting](#ast-before-and-after-formatting) for more discussion.
223 _Black_ will add trailing commas to expressions that are split by comma where each
224 element is on its own line. This includes function signatures.
226 One exception to adding trailing commas is function signatures containing `*`, `*args`,
227 or `**kwargs`. In this case a trailing comma is only safe to use on Python 3.6. _Black_
228 will detect if your file is already 3.6+ only and use trailing commas in this situation.
229 If you wonder how it knows, it looks for f-strings and existing use of trailing commas
230 in function signatures that have stars in them. In other words, if you'd like a trailing
231 comma in this situation and _Black_ didn't recognize it was safe to do so, put it there
232 manually and _Black_ will keep it.
234 A pre-existing trailing comma informs _Black_ to always explode contents of the current
235 bracket pair into one item per line. Read more about this in the
236 [Pragmatism](#pragmatism) section below.
240 _Black_ prefers double quotes (`"` and `"""`) over single quotes (`'` and `'''`). It
241 will replace the latter with the former as long as it does not result in more backslash
244 _Black_ also standardizes string prefixes. Prefix characters are made lowercase with the
245 exception of [capital "R" prefixes](#rstrings-and-rstrings), unicode literal markers
246 (`u`) are removed because they are meaningless in Python 3, and in the case of multiple
247 characters "r" is put first as in spoken language: "raw f-string".
249 The main reason to standardize on a single form of quotes is aesthetics. Having one kind
250 of quotes everywhere reduces reader distraction. It will also enable a future version of
251 _Black_ to merge consecutive string literals that ended up on the same line (see
252 [#26](https://github.com/psf/black/issues/26) for details).
254 Why settle on double quotes? They anticipate apostrophes in English text. They match the
255 docstring standard described in
256 [PEP 257](https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring). An empty
257 string in double quotes (`""`) is impossible to confuse with a one double-quote
258 regardless of fonts and syntax highlighting used. On top of this, double quotes for
259 strings are consistent with C which Python interacts a lot with.
261 On certain keyboard layouts like US English, typing single quotes is a bit easier than
262 double quotes. The latter requires use of the Shift key. My recommendation here is to
263 keep using whatever is faster to type and let _Black_ handle the transformation.
265 If you are adopting _Black_ in a large project with pre-existing string conventions
267 ["single quotes for data, double quotes for human-readable strings"](https://stackoverflow.com/a/56190)),
268 you can pass `--skip-string-normalization` on the command line. This is meant as an
269 adoption helper, avoid using this for new projects.
271 _Black_ also processes docstrings. Firstly the indentation of docstrings is corrected
272 for both quotations and the text within, although relative indentation in the text is
273 preserved. Superfluous trailing whitespace on each line and unnecessary new lines at the
274 end of the docstring are removed. All leading tabs are converted to spaces, but tabs
275 inside text are preserved. Whitespace leading and trailing one-line docstrings is
280 _Black_ standardizes most numeric literals to use lowercase letters for the syntactic
281 parts and uppercase letters for the digits themselves: `0xAB` instead of `0XAB` and
282 `1e10` instead of `1E10`.
284 ### Line breaks & binary operators
286 _Black_ will break a line before a binary operator when splitting a block of code over
287 multiple lines. This is so that _Black_ is compliant with the recent changes in the
288 [PEP 8](https://www.python.org/dev/peps/pep-0008/#should-a-line-break-before-or-after-a-binary-operator)
289 style guide, which emphasizes that this approach improves readability.
291 Almost all operators will be surrounded by single spaces, the only exceptions are unary
292 operators (`+`, `-`, and `~`), and power operators when both operands are simple. For
293 powers, an operand is considered simple if it's only a NAME, numeric CONSTANT, or
294 attribute access (chained attribute access is allowed), with or without a preceding
298 # For example, these won't be surrounded by whitespace
301 c = config.base**runtime.config.exponent
305 # ... but these will be surrounded by whitespace
306 f = 2 ** get_exponent()
307 g = get_x() ** get_y()
308 h = config['base'] ** 2
314 [recommends](https://www.python.org/dev/peps/pep-0008/#whitespace-in-expressions-and-statements)
315 to treat `:` in slices as a binary operator with the lowest priority, and to leave an
316 equal amount of space on either side, except if a parameter is omitted (e.g.
317 `ham[1 + 1 :]`). It recommends no spaces around `:` operators for "simple expressions"
318 (`ham[lower:upper]`), and extra space for "complex expressions"
319 (`ham[lower : upper + offset]`). _Black_ treats anything more than variable names as
320 "complex" (`ham[lower : upper + 1]`). It also states that for extended slices, both `:`
321 operators have to have the same amount of spacing, except if a parameter is omitted
322 (`ham[1 + 1 ::]`). _Black_ enforces these rules consistently.
324 This behaviour may raise `E203 whitespace before ':'` warnings in style guide
325 enforcement tools like Flake8. Since `E203` is not PEP 8 compliant, you should tell
326 Flake8 to ignore these warnings.
330 Some parentheses are optional in the Python grammar. Any expression can be wrapped in a
331 pair of parentheses to form an atom. There are a few interesting cases:
335 - `for (...) in (...):`
336 - `assert (...), (...)`
337 - `from X import (...)`
340 - `target: type = (...)`
341 - `some, *un, packing = (...)`
342 - `augmented += (...)`
344 In those cases, parentheses are removed when the entire statement fits in one line, or
345 if the inner expression doesn't have any delimiters to further split on. If there is
346 only a single delimiter and the expression starts or ends with a bracket, the
347 parentheses can also be successfully omitted since the existing bracket pair will
348 organize the expression neatly anyway. Otherwise, the parentheses are added.
350 Please note that _Black_ does not add or remove any additional nested parentheses that
351 you might want to have for clarity or further code organization. For example those
352 parentheses are not going to be removed:
355 return not (this or that)
356 decision = (maybe.this() and values > 0) or (maybe.that() and values < 0)
361 Some popular APIs, like ORMs, use call chaining. This API style is known as a
362 [fluent interface](https://en.wikipedia.org/wiki/Fluent_interface). _Black_ formats
363 those by treating dots that follow a call or an indexing operation like a very low
364 priority delimiter. It's easier to show the behavior than to explain it. Look at the
368 def example(session):
370 session.query(models.Customer.id)
372 models.Customer.account_id == account_id,
373 models.Customer.email == email_address,
375 .order_by(models.Customer.id.asc())
380 ### Typing stub files
382 PEP 484 describes the syntax for type hints in Python. One of the use cases for typing
383 is providing type annotations for modules which cannot contain them directly (they might
384 be written in C, or they might be third-party, or their implementation may be overly
388 [stub files with the `.pyi` file extension](https://www.python.org/dev/peps/pep-0484/#stub-files)
389 can be used to describe typing information for an external module. Those stub files omit
390 the implementation of classes and functions they describe, instead they only contain the
391 structure of the file (listing globals, functions, and classes with their members). The
392 recommended code style for those files is more terse than PEP 8:
394 - prefer `...` on the same line as the class/function signature;
395 - avoid vertical whitespace between consecutive module-level functions, names, or
396 methods and fields within a single class;
397 - use a single blank line between top-level class definitions, or none if the classes
400 _Black_ enforces the above rules. There are additional guidelines for formatting `.pyi`
401 file that are not enforced yet but might be in a future version of the formatter:
403 - prefer `...` over `pass`;
404 - avoid using string literals in type annotations, stub files support forward references
405 natively (like Python 3.7 code with `from __future__ import annotations`);
406 - use variable annotations instead of type comments, even for stubs that target older
411 _Black_ will normalize line endings (`\n` or `\r\n`) based on the first line ending of
416 Early versions of _Black_ used to be absolutist in some respects. They took after its
417 initial author. This was fine at the time as it made the implementation simpler and
418 there were not many users anyway. Not many edge cases were reported. As a mature tool,
419 _Black_ does make some exceptions to rules it otherwise holds. This section documents
420 what those exceptions are and why this is the case.
422 ### The magic trailing comma
424 _Black_ in general does not take existing formatting into account.
426 However, there are cases where you put a short collection or function call in your code
427 but you anticipate it will grow in the future.
433 "en_us": "English (US)",
438 Early versions of _Black_ used to ruthlessly collapse those into one line (it fits!).
439 Now, you can communicate that you don't want that by putting a trailing comma in the
440 collection yourself. When you do, _Black_ will know to always explode your collection
441 into one item per line.
443 How do you make it stop? Just delete that trailing comma and _Black_ will collapse your
444 collection into one line if it fits.
446 If you must, you can recover the behaviour of early versions of _Black_ with the option
447 `--skip-magic-trailing-comma` / `-C`.
449 ### r"strings" and R"strings"
451 _Black_ normalizes string quotes as well as string prefixes, making them lowercase. One
452 exception to this rule is r-strings. It turns out that the very popular
453 [MagicPython](https://github.com/MagicStack/MagicPython/) syntax highlighter, used by
454 default by (among others) GitHub and Visual Studio Code, differentiates between
455 r-strings and R-strings. The former are syntax highlighted as regular expressions while
456 the latter are treated as true raw strings with no special semantics.
458 ### AST before and after formatting
460 When run with `--safe` (the default), _Black_ checks that the code before and after is
461 semantically equivalent. This check is done by comparing the AST of the source with the
462 AST of the target. There are three limited cases in which the AST does differ:
464 1. _Black_ cleans up leading and trailing whitespace of docstrings, re-indenting them if
465 needed. It's been one of the most popular user-reported features for the formatter to
466 fix whitespace issues with docstrings. While the result is technically an AST
467 difference, due to the various possibilities of forming docstrings, all real-world
468 uses of docstrings that we're aware of sanitize indentation and leading/trailing
471 1. _Black_ manages optional parentheses for some statements. In the case of the `del`
472 statement, presence of wrapping parentheses or lack of thereof changes the resulting
473 AST but is semantically equivalent in the interpreter.
475 1. _Black_ might move comments around, which includes type comments. Those are part of
476 the AST as of Python 3.8. While the tool implements a number of special cases for
477 those comments, there is no guarantee they will remain where they were in the source.
478 Note that this doesn't change runtime behavior of the source code.
480 To put things in perspective, the code equivalence check is a feature of _Black_ which
481 other formatters don't implement at all. It is of crucial importance to us to ensure
482 code behaves the way it did before it got reformatted. We treat this as a feature and
483 there are no plans to relax this in the future. The exceptions enumerated above stem
484 from either user feedback or implementation details of the tool. In each case we made
485 due diligence to ensure that the AST divergence is of no practical consequence.