]> git.madduck.net Git - etc/vim.git/blob - README.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 Primer badge to README.md (#1454)
[etc/vim.git] / README.md
1 ![Black Logo](https://raw.githubusercontent.com/psf/black/master/docs/_static/logo2-readme.png)
2
3 <h2 align="center">The Uncompromising Code Formatter</h2>
4
5 <p align="center">
6 <a href="https://travis-ci.com/psf/black"><img alt="Build Status" src="https://travis-ci.com/psf/black.svg?branch=master"></a>
7 <a href="https://github.com/psf/black/actions"><img alt="Actions Status" src="https://github.com/psf/black/workflows/Test/badge.svg"></a>
8 <a href="https://github.com/psf/black/actions"><img alt="Actions Status" src="https://github.com/psf/black/workflows/Primer/badge.svg"></a>
9 <a href="https://black.readthedocs.io/en/stable/?badge=stable"><img alt="Documentation Status" src="https://readthedocs.org/projects/black/badge/?version=stable"></a>
10 <a href="https://coveralls.io/github/psf/black?branch=master"><img alt="Coverage Status" src="https://coveralls.io/repos/github/psf/black/badge.svg?branch=master"></a>
11 <a href="https://github.com/psf/black/blob/master/LICENSE"><img alt="License: MIT" src="https://black.readthedocs.io/en/stable/_static/license.svg"></a>
12 <a href="https://pypi.org/project/black/"><img alt="PyPI" src="https://img.shields.io/pypi/v/black"></a>
13 <a href="https://pepy.tech/project/black"><img alt="Downloads" src="https://pepy.tech/badge/black"></a>
14 <a href="https://github.com/psf/black"><img alt="Code style: black" src="https://img.shields.io/badge/code%20style-black-000000.svg"></a>
15 </p>
16
17 > “Any color you like.”
18
19 _Black_ is the uncompromising Python code formatter. By using it, you agree to cede
20 control over minutiae of hand-formatting. In return, _Black_ gives you speed,
21 determinism, and freedom from `pycodestyle` nagging about formatting. You will save time
22 and mental energy for more important matters.
23
24 Blackened code looks the same regardless of the project you're reading. Formatting
25 becomes transparent after a while and you can focus on the content instead.
26
27 _Black_ makes code review faster by producing the smallest diffs possible.
28
29 Try it out now using the [Black Playground](https://black.now.sh). Watch the
30 [PyCon 2019 talk](https://youtu.be/esZLCuWs_2Y) to learn more.
31
32 ---
33
34 _Contents:_ **[Installation and usage](#installation-and-usage)** |
35 **[Code style](#the-black-code-style)** | **[Pragmatism](#pragmatism)** |
36 **[pyproject.toml](#pyprojecttoml)** | **[Editor integration](#editor-integration)** |
37 **[blackd](#blackd)** | **[black-primer](#black-primer)** |
38 **[Version control integration](#version-control-integration)** |
39 **[Ignoring unmodified files](#ignoring-unmodified-files)** | **[Used by](#used-by)** |
40 **[Testimonials](#testimonials)** | **[Show your style](#show-your-style)** |
41 **[Contributing](#contributing-to-black)** | **[Change Log](#change-log)** |
42 **[Authors](#authors)**
43
44 ---
45
46 ## Installation and usage
47
48 ### Installation
49
50 _Black_ can be installed by running `pip install black`. It requires Python 3.6.0+ to
51 run but you can reformat Python 2 code with it, too.
52
53 ### Usage
54
55 To get started right away with sensible defaults:
56
57 ```sh
58 black {source_file_or_directory}
59 ```
60
61 ### Command line options
62
63 _Black_ doesn't provide many options. You can list them by running `black --help`:
64
65 ```text
66 Usage: black [OPTIONS] [SRC]...
67
68   The uncompromising code formatter.
69
70 Options:
71   -c, --code TEXT                 Format the code passed in as a string.
72   -l, --line-length INTEGER       How many characters per line to allow.
73                                   [default: 88]
74
75   -t, --target-version [py27|py33|py34|py35|py36|py37|py38]
76                                   Python versions that should be supported by
77                                   Black's output. [default: per-file auto-
78                                   detection]
79
80   --pyi                           Format all input files like typing stubs
81                                   regardless of file extension (useful when
82                                   piping source on standard input).
83
84   -S, --skip-string-normalization
85                                   Don't normalize string quotes or prefixes.
86   --check                         Don't write the files back, just return the
87                                   status.  Return code 0 means nothing would
88                                   change.  Return code 1 means some files
89                                   would be reformatted. Return code 123 means
90                                   there was an internal error.
91
92   --diff                          Don't write the files back, just output a
93                                   diff for each file on stdout.
94
95   --color / --no-color            Show colored diff. Only applies when
96                                   `--diff` is given.
97
98   --fast / --safe                 If --fast given, skip temporary sanity
99                                   checks. [default: --safe]
100
101   --include TEXT                  A regular expression that matches files and
102                                   directories that should be included on
103                                   recursive searches.  An empty value means
104                                   all files are included regardless of the
105                                   name.  Use forward slashes for directories
106                                   on all platforms (Windows, too).  Exclusions
107                                   are calculated first, inclusions later.
108                                   [default: \.pyi?$]
109
110   --exclude TEXT                  A regular expression that matches files and
111                                   directories that should be excluded on
112                                   recursive searches.  An empty value means no
113                                   paths are excluded. Use forward slashes for
114                                   directories on all platforms (Windows, too).
115                                   Exclusions are calculated first, inclusions
116                                   later.  [default: /(\.eggs|\.git|\.hg|\.mypy
117                                   _cache|\.nox|\.tox|\.venv|\.svn|_build|buck-
118                                   out|build|dist)/]
119
120   --force-exclude TEXT            Like --exclude, but files and directories
121                                   matching this regex will be excluded even
122                                   when they are passed explicitly as arguments
123
124   -q, --quiet                     Don't emit non-error messages to stderr.
125                                   Errors are still emitted; silence those with
126                                   2>/dev/null.
127
128   -v, --verbose                   Also emit messages to stderr about files
129                                   that were not changed or were ignored due to
130                                   --exclude=.
131
132   --version                       Show the version and exit.
133   --config FILE                   Read configuration from PATH.
134   -h, --help                      Show this message and exit.
135 ```
136
137 _Black_ is a well-behaved Unix-style command-line tool:
138
139 - it does nothing if no sources are passed to it;
140 - it will read from standard input and write to standard output if `-` is used as the
141   filename;
142 - it only outputs messages to users on standard error;
143 - exits with code 0 unless an internal error occurred (or `--check` was used).
144
145 ### Using _Black_ with other tools
146
147 While _Black_ enforces formatting that conforms to PEP 8, other tools may raise warnings
148 about _Black_'s changes or will overwrite _Black_'s changes. A good example of this is
149 [isort](https://pypi.org/p/isort). Since _Black_ is barely configurable, these tools
150 should be configured to neither warn about nor overwrite _Black_'s changes.
151
152 Actual details on _Black_ compatible configurations for various tools can be found in
153 [compatible_configs](https://github.com/psf/black/blob/master/docs/compatible_configs.md).
154
155 ### Migrating your code style without ruining git blame
156
157 A long-standing argument against moving to automated code formatters like _Black_ is
158 that the migration will clutter up the output of `git blame`. This was a valid argument,
159 but since Git version 2.23, Git natively supports
160 [ignoring revisions in blame](https://git-scm.com/docs/git-blame#Documentation/git-blame.txt---ignore-revltrevgt)
161 with the `--ignore-rev` option. You can also pass a file listing the revisions to ignore
162 using the `--ignore-revs-file` option. The changes made by the revision will be ignored
163 when assigning blame. Lines modified by an ignored revision will be blamed on the
164 previous revision that modified those lines.
165
166 So when migrating your project's code style to _Black_, reformat everything and commit
167 the changes (preferably in one massive commit). Then put the full 40 characters commit
168 identifier(s) into a file.
169
170 ```
171 # Migrate code style to Black
172 5b4ab991dede475d393e9d69ec388fd6bd949699
173 ```
174
175 Afterwards, you can pass that file to `git blame` and see clean and meaningful blame
176 information.
177
178 ```console
179 $ git blame important.py --ignore-revs-file .git-blame-ignore-revs
180 7a1ae265 (John Smith 2019-04-15 15:55:13 -0400 1) def very_important_function(text, file):
181 abdfd8b0 (Alice Doe  2019-09-23 11:39:32 -0400 2)     text = text.lstrip()
182 7a1ae265 (John Smith 2019-04-15 15:55:13 -0400 3)     with open(file, "r+") as f:
183 7a1ae265 (John Smith 2019-04-15 15:55:13 -0400 4)         f.write(formatted)
184 ```
185
186 You can even configure `git` to automatically ignore revisions listed in a file on every
187 call to `git blame`.
188
189 ```console
190 $ git config blame.ignoreRevsFile .git-blame-ignore-revs
191 ```
192
193 **The one caveat is that GitHub and GitLab do not yet support ignoring revisions using
194 their native UI of blame.** So blame information will be cluttered with a reformatting
195 commit on those platforms. (If you'd like this feature, there's an open issue for
196 [GitLab](https://gitlab.com/gitlab-org/gitlab/-/issues/31423) and please let GitHub
197 know!)
198
199 ### NOTE: This is a beta product
200
201 _Black_ is already [successfully used](#used-by) by many projects, small and big. It
202 also sports a decent test suite. However, it is still very new. Things will probably be
203 wonky for a while. This is made explicit by the "Beta" trove classifier, as well as by
204 the "b" in the version number. What this means for you is that **until the formatter
205 becomes stable, you should expect some formatting to change in the future**. That being
206 said, no drastic stylistic changes are planned, mostly responses to bug reports.
207
208 Also, as a temporary safety measure, _Black_ will check that the reformatted code still
209 produces a valid AST that is equivalent to the original. This slows it down. If you're
210 feeling confident, use `--fast`.
211
212 ## The _Black_ code style
213
214 _Black_ reformats entire files in place. It is not configurable. It doesn't take
215 previous formatting into account. It doesn't reformat blocks that start with
216 `# fmt: off` and end with `# fmt: on`. `# fmt: on/off` have to be on the same level of
217 indentation. It also recognizes [YAPF](https://github.com/google/yapf)'s block comments
218 to the same effect, as a courtesy for straddling code.
219
220 ### How _Black_ wraps lines
221
222 _Black_ ignores previous formatting and applies uniform horizontal and vertical
223 whitespace to your code. The rules for horizontal whitespace can be summarized as: do
224 whatever makes `pycodestyle` happy. The coding style used by _Black_ can be viewed as a
225 strict subset of PEP 8.
226
227 As for vertical whitespace, _Black_ tries to render one full expression or simple
228 statement per line. If this fits the allotted line length, great.
229
230 ```py3
231 # in:
232
233 j = [1,
234      2,
235      3
236 ]
237
238 # out:
239
240 j = [1, 2, 3]
241 ```
242
243 If not, _Black_ will look at the contents of the first outer matching brackets and put
244 that in a separate indented line.
245
246 ```py3
247 # in:
248
249 ImportantClass.important_method(exc, limit, lookup_lines, capture_locals, extra_argument)
250
251 # out:
252
253 ImportantClass.important_method(
254     exc, limit, lookup_lines, capture_locals, extra_argument
255 )
256 ```
257
258 If that still doesn't fit the bill, it will decompose the internal expression further
259 using the same rule, indenting matching brackets every time. If the contents of the
260 matching brackets pair are comma-separated (like an argument list, or a dict literal,
261 and so on) then _Black_ will first try to keep them on the same line with the matching
262 brackets. If that doesn't work, it will put all of them in separate lines.
263
264 ```py3
265 # in:
266
267 def very_important_function(template: str, *variables, file: os.PathLike, engine: str, header: bool = True, debug: bool = False):
268     """Applies `variables` to the `template` and writes to `file`."""
269     with open(file, 'w') as f:
270         ...
271
272 # out:
273
274 def very_important_function(
275     template: str,
276     *variables,
277     file: os.PathLike,
278     engine: str,
279     header: bool = True,
280     debug: bool = False,
281 ):
282     """Applies `variables` to the `template` and writes to `file`."""
283     with open(file, "w") as f:
284         ...
285 ```
286
287 _Black_ prefers parentheses over backslashes, and will remove backslashes if found.
288
289 ```py3
290 # in:
291
292 if some_short_rule1 \
293   and some_short_rule2:
294       ...
295
296 # out:
297
298 if some_short_rule1 and some_short_rule2:
299   ...
300
301
302 # in:
303
304 if some_long_rule1 \
305   and some_long_rule2:
306     ...
307
308 # out:
309
310 if (
311     some_long_rule1
312     and some_long_rule2
313 ):
314     ...
315
316 ```
317
318 Backslashes and multiline strings are one of the two places in the Python grammar that
319 break significant indentation. You never need backslashes, they are used to force the
320 grammar to accept breaks that would otherwise be parse errors. That makes them confusing
321 to look at and brittle to modify. This is why _Black_ always gets rid of them.
322
323 If you're reaching for backslashes, that's a clear signal that you can do better if you
324 slightly refactor your code. I hope some of the examples above show you that there are
325 many ways in which you can do it.
326
327 However there is one exception: `with` statements using multiple context managers.
328 Python's grammar does not allow organizing parentheses around the series of context
329 managers.
330
331 We don't want formatting like:
332
333 ```py3
334 with make_context_manager1() as cm1, make_context_manager2() as cm2, make_context_manager3() as cm3, make_context_manager4() as cm4:
335     ...  # nothing to split on - line too long
336 ```
337
338 So _Black_ will now format it like this:
339
340 ```py3
341 with \
342      make_context_manager(1) as cm1, \
343      make_context_manager(2) as cm2, \
344      make_context_manager(3) as cm3, \
345      make_context_manager(4) as cm4 \
346 :
347     ...  # backslashes and an ugly stranded colon
348 ```
349
350 You might have noticed that closing brackets are always dedented and that a trailing
351 comma is always added. Such formatting produces smaller diffs; when you add or remove an
352 element, it's always just one line. Also, having the closing bracket dedented provides a
353 clear delimiter between two distinct sections of the code that otherwise share the same
354 indentation level (like the arguments list and the docstring in the example above).
355
356 If a data structure literal (tuple, list, set, dict) or a line of "from" imports cannot
357 fit in the allotted length, it's always split into one element per line. This minimizes
358 diffs as well as enables readers of code to find which commit introduced a particular
359 entry. This also makes _Black_ compatible with [isort](https://pypi.org/p/isort/) with
360 the following configuration.
361
362 <details>
363 <summary>A compatible `.isort.cfg`</summary>
364
365 ```
366 [settings]
367 multi_line_output=3
368 include_trailing_comma=True
369 force_grid_wrap=0
370 use_parentheses=True
371 line_length=88
372 ```
373
374 The equivalent command line is:
375
376 ```
377 $ isort --multi-line=3 --trailing-comma --force-grid-wrap=0 --use-parentheses --line-width=88 [ file.py ]
378 ```
379
380 </details>
381
382 ### Line length
383
384 You probably noticed the peculiar default line length. _Black_ defaults to 88 characters
385 per line, which happens to be 10% over 80. This number was found to produce
386 significantly shorter files than sticking with 80 (the most popular), or even 79 (used
387 by the standard library). In general,
388 [90-ish seems like the wise choice](https://youtu.be/wf-BqAjZb8M?t=260).
389
390 If you're paid by the line of code you write, you can pass `--line-length` with a lower
391 number. _Black_ will try to respect that. However, sometimes it won't be able to without
392 breaking other rules. In those rare cases, auto-formatted code will exceed your allotted
393 limit.
394
395 You can also increase it, but remember that people with sight disabilities find it
396 harder to work with line lengths exceeding 100 characters. It also adversely affects
397 side-by-side diff review on typical screen resolutions. Long lines also make it harder
398 to present code neatly in documentation or talk slides.
399
400 If you're using Flake8, you can bump `max-line-length` to 88 and forget about it.
401 Alternatively, use [Bugbear](https://github.com/PyCQA/flake8-bugbear)'s B950 warning
402 instead of E501 and keep the max line length at 80 which you are probably already using.
403 You'd do it like this:
404
405 ```ini
406 [flake8]
407 max-line-length = 80
408 ...
409 select = C,E,F,W,B,B950
410 ignore = E203, E501, W503
411 ```
412
413 You'll find _Black_'s own .flake8 config file is configured like this. Explanation of
414 why W503 and E203 are disabled can be found further in this documentation. And if you're
415 curious about the reasoning behind B950,
416 [Bugbear's documentation](https://github.com/PyCQA/flake8-bugbear#opinionated-warnings)
417 explains it. The tl;dr is "it's like highway speed limits, we won't bother you if you
418 overdo it by a few km/h".
419
420 **If you're looking for a minimal, black-compatible flake8 configuration:**
421
422 ```ini
423 [flake8]
424 max-line-length = 88
425 extend-ignore = E203
426 ```
427
428 ### Empty lines
429
430 _Black_ avoids spurious vertical whitespace. This is in the spirit of PEP 8 which says
431 that in-function vertical whitespace should only be used sparingly.
432
433 _Black_ will allow single empty lines inside functions, and single and double empty
434 lines on module level left by the original editors, except when they're within
435 parenthesized expressions. Since such expressions are always reformatted to fit minimal
436 space, this whitespace is lost.
437
438 It will also insert proper spacing before and after function definitions. It's one line
439 before and after inner functions and two lines before and after module-level functions
440 and classes. _Black_ will not put empty lines between function/class definitions and
441 standalone comments that immediately precede the given function/class.
442
443 _Black_ will enforce single empty lines between a class-level docstring and the first
444 following field or method. This conforms to
445 [PEP 257](https://www.python.org/dev/peps/pep-0257/#multi-line-docstrings).
446
447 _Black_ won't insert empty lines after function docstrings unless that empty line is
448 required due to an inner function starting immediately after.
449
450 ### Trailing commas
451
452 _Black_ will add trailing commas to expressions that are split by comma where each
453 element is on its own line. This includes function signatures.
454
455 Unnecessary trailing commas are removed if an expression fits in one line. This makes it
456 1% more likely that your line won't exceed the allotted line length limit. Moreover, in
457 this scenario, if you added another argument to your call, you'd probably fit it in the
458 same line anyway. That doesn't make diffs any larger.
459
460 One exception to removing trailing commas is tuple expressions with just one element. In
461 this case _Black_ won't touch the single trailing comma as this would unexpectedly
462 change the underlying data type. Note that this is also the case when commas are used
463 while indexing. This is a tuple in disguise: `numpy_array[3, ]`.
464
465 One exception to adding trailing commas is function signatures containing `*`, `*args`,
466 or `**kwargs`. In this case a trailing comma is only safe to use on Python 3.6. _Black_
467 will detect if your file is already 3.6+ only and use trailing commas in this situation.
468 If you wonder how it knows, it looks for f-strings and existing use of trailing commas
469 in function signatures that have stars in them. In other words, if you'd like a trailing
470 comma in this situation and _Black_ didn't recognize it was safe to do so, put it there
471 manually and _Black_ will keep it.
472
473 ### Strings
474
475 _Black_ prefers double quotes (`"` and `"""`) over single quotes (`'` and `'''`). It
476 will replace the latter with the former as long as it does not result in more backslash
477 escapes than before.
478
479 _Black_ also standardizes string prefixes, making them always lowercase. On top of that,
480 if your code is already Python 3.6+ only or it's using the `unicode_literals` future
481 import, _Black_ will remove `u` from the string prefix as it is meaningless in those
482 scenarios.
483
484 The main reason to standardize on a single form of quotes is aesthetics. Having one kind
485 of quotes everywhere reduces reader distraction. It will also enable a future version of
486 _Black_ to merge consecutive string literals that ended up on the same line (see
487 [#26](https://github.com/psf/black/issues/26) for details).
488
489 Why settle on double quotes? They anticipate apostrophes in English text. They match the
490 docstring standard described in
491 [PEP 257](https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring). An empty
492 string in double quotes (`""`) is impossible to confuse with a one double-quote
493 regardless of fonts and syntax highlighting used. On top of this, double quotes for
494 strings are consistent with C which Python interacts a lot with.
495
496 On certain keyboard layouts like US English, typing single quotes is a bit easier than
497 double quotes. The latter requires use of the Shift key. My recommendation here is to
498 keep using whatever is faster to type and let _Black_ handle the transformation.
499
500 If you are adopting _Black_ in a large project with pre-existing string conventions
501 (like the popular
502 ["single quotes for data, double quotes for human-readable strings"](https://stackoverflow.com/a/56190)),
503 you can pass `--skip-string-normalization` on the command line. This is meant as an
504 adoption helper, avoid using this for new projects.
505
506 ### Numeric literals
507
508 _Black_ standardizes most numeric literals to use lowercase letters for the syntactic
509 parts and uppercase letters for the digits themselves: `0xAB` instead of `0XAB` and
510 `1e10` instead of `1E10`. Python 2 long literals are styled as `2L` instead of `2l` to
511 avoid confusion between `l` and `1`.
512
513 ### Line breaks & binary operators
514
515 _Black_ will break a line before a binary operator when splitting a block of code over
516 multiple lines. This is so that _Black_ is compliant with the recent changes in the
517 [PEP 8](https://www.python.org/dev/peps/pep-0008/#should-a-line-break-before-or-after-a-binary-operator)
518 style guide, which emphasizes that this approach improves readability.
519
520 This behaviour may raise `W503 line break before binary operator` warnings in style
521 guide enforcement tools like Flake8. Since `W503` is not PEP 8 compliant, you should
522 tell Flake8 to ignore these warnings.
523
524 ### Slices
525
526 PEP 8
527 [recommends](https://www.python.org/dev/peps/pep-0008/#whitespace-in-expressions-and-statements)
528 to treat `:` in slices as a binary operator with the lowest priority, and to leave an
529 equal amount of space on either side, except if a parameter is omitted (e.g.
530 `ham[1 + 1 :]`). It recommends no spaces around `:` operators for "simple expressions"
531 (`ham[lower:upper]`), and extra space for "complex expressions"
532 (`ham[lower : upper + offset]`). _Black_ treats anything more than variable names as
533 "complex" (`ham[lower : upper + 1]`). It also states that for extended slices, both `:`
534 operators have to have the same amount of spacing, except if a parameter is omitted
535 (`ham[1 + 1 ::]`). _Black_ enforces these rules consistently.
536
537 This behaviour may raise `E203 whitespace before ':'` warnings in style guide
538 enforcement tools like Flake8. Since `E203` is not PEP 8 compliant, you should tell
539 Flake8 to ignore these warnings.
540
541 ### Parentheses
542
543 Some parentheses are optional in the Python grammar. Any expression can be wrapped in a
544 pair of parentheses to form an atom. There are a few interesting cases:
545
546 - `if (...):`
547 - `while (...):`
548 - `for (...) in (...):`
549 - `assert (...), (...)`
550 - `from X import (...)`
551 - assignments like:
552   - `target = (...)`
553   - `target: type = (...)`
554   - `some, *un, packing = (...)`
555   - `augmented += (...)`
556
557 In those cases, parentheses are removed when the entire statement fits in one line, or
558 if the inner expression doesn't have any delimiters to further split on. If there is
559 only a single delimiter and the expression starts or ends with a bracket, the
560 parenthesis can also be successfully omitted since the existing bracket pair will
561 organize the expression neatly anyway. Otherwise, the parentheses are added.
562
563 Please note that _Black_ does not add or remove any additional nested parentheses that
564 you might want to have for clarity or further code organization. For example those
565 parentheses are not going to be removed:
566
567 ```py3
568 return not (this or that)
569 decision = (maybe.this() and values > 0) or (maybe.that() and values < 0)
570 ```
571
572 ### Call chains
573
574 Some popular APIs, like ORMs, use call chaining. This API style is known as a
575 [fluent interface](https://en.wikipedia.org/wiki/Fluent_interface). _Black_ formats
576 those by treating dots that follow a call or an indexing operation like a very low
577 priority delimiter. It's easier to show the behavior than to explain it. Look at the
578 example:
579
580 ```py3
581 def example(session):
582     result = (
583         session.query(models.Customer.id)
584         .filter(
585             models.Customer.account_id == account_id,
586             models.Customer.email == email_address,
587         )
588         .order_by(models.Customer.id.asc())
589         .all()
590     )
591 ```
592
593 ### Typing stub files
594
595 PEP 484 describes the syntax for type hints in Python. One of the use cases for typing
596 is providing type annotations for modules which cannot contain them directly (they might
597 be written in C, or they might be third-party, or their implementation may be overly
598 dynamic, and so on).
599
600 To solve this,
601 [stub files with the `.pyi` file extension](https://www.python.org/dev/peps/pep-0484/#stub-files)
602 can be used to describe typing information for an external module. Those stub files omit
603 the implementation of classes and functions they describe, instead they only contain the
604 structure of the file (listing globals, functions, and classes with their members). The
605 recommended code style for those files is more terse than PEP 8:
606
607 - prefer `...` on the same line as the class/function signature;
608 - avoid vertical whitespace between consecutive module-level functions, names, or
609   methods and fields within a single class;
610 - use a single blank line between top-level class definitions, or none if the classes
611   are very small.
612
613 _Black_ enforces the above rules. There are additional guidelines for formatting `.pyi`
614 file that are not enforced yet but might be in a future version of the formatter:
615
616 - all function bodies should be empty (contain `...` instead of the body);
617 - do not use docstrings;
618 - prefer `...` over `pass`;
619 - for arguments with a default, use `...` instead of the actual default;
620 - avoid using string literals in type annotations, stub files support forward references
621   natively (like Python 3.7 code with `from __future__ import annotations`);
622 - use variable annotations instead of type comments, even for stubs that target older
623   versions of Python;
624 - for arguments that default to `None`, use `Optional[]` explicitly;
625 - use `float` instead of `Union[int, float]`.
626
627 ## Pragmatism
628
629 Early versions of _Black_ used to be absolutist in some respects. They took after its
630 initial author. This was fine at the time as it made the implementation simpler and
631 there were not many users anyway. Not many edge cases were reported. As a mature tool,
632 _Black_ does make some exceptions to rules it otherwise holds. This section documents
633 what those exceptions are and why this is the case.
634
635 ### The magic trailing comma
636
637 _Black_ in general does not take existing formatting into account.
638
639 However, there are cases where you put a short collection or function call in your code
640 but you anticipate it will grow in the future.
641
642 For example:
643
644 ```py3
645 TRANSLATIONS = {
646     "en_us": "English (US)",
647     "pl_pl": "polski",
648 }
649 ```
650
651 Early versions of _Black_ used to ruthlessly collapse those into one line (it fits!).
652 Now, you can communicate that you don't want that by putting a trailing comma in the
653 collection yourself. When you do, _Black_ will know to always explode your collection
654 into one item per line.
655
656 How do you make it stop? Just delete that trailing comma and _Black_ will collapse your
657 collection into one line if it fits.
658
659 ### r"strings" and R"strings"
660
661 _Black_ normalizes string quotes as well as string prefixes, making them lowercase. One
662 exception to this rule is r-strings. It turns out that the very popular
663 [MagicPython](https://github.com/MagicStack/MagicPython/) syntax highlighter, used by
664 default by (among others) GitHub and Visual Studio Code, differentiates between
665 r-strings and R-strings. The former are syntax highlighted as regular expressions while
666 the latter are treated as true raw strings with no special semantics.
667
668 ## pyproject.toml
669
670 _Black_ is able to read project-specific default values for its command line options
671 from a `pyproject.toml` file. This is especially useful for specifying custom
672 `--include` and `--exclude` patterns for your project.
673
674 **Pro-tip**: If you're asking yourself "Do I need to configure anything?" the answer is
675 "No". _Black_ is all about sensible defaults.
676
677 ### What on Earth is a `pyproject.toml` file?
678
679 [PEP 518](https://www.python.org/dev/peps/pep-0518/) defines `pyproject.toml` as a
680 configuration file to store build system requirements for Python projects. With the help
681 of tools like [Poetry](https://poetry.eustace.io/) or
682 [Flit](https://flit.readthedocs.io/en/latest/) it can fully replace the need for
683 `setup.py` and `setup.cfg` files.
684
685 ### Where _Black_ looks for the file
686
687 By default _Black_ looks for `pyproject.toml` starting from the common base directory of
688 all files and directories passed on the command line. If it's not there, it looks in
689 parent directories. It stops looking when it finds the file, or a `.git` directory, or a
690 `.hg` directory, or the root of the file system, whichever comes first.
691
692 If you're formatting standard input, _Black_ will look for configuration starting from
693 the current working directory.
694
695 You can also explicitly specify the path to a particular file that you want with
696 `--config`. In this situation _Black_ will not look for any other file.
697
698 If you're running with `--verbose`, you will see a blue message if a file was found and
699 used.
700
701 Please note `blackd` will not use `pyproject.toml` configuration.
702
703 ### Configuration format
704
705 As the file extension suggests, `pyproject.toml` is a
706 [TOML](https://github.com/toml-lang/toml) file. It contains separate sections for
707 different tools. _Black_ is using the `[tool.black]` section. The option keys are the
708 same as long names of options on the command line.
709
710 Note that you have to use single-quoted strings in TOML for regular expressions. It's
711 the equivalent of r-strings in Python. Multiline strings are treated as verbose regular
712 expressions by Black. Use `[ ]` to denote a significant space character.
713
714 <details>
715 <summary>Example `pyproject.toml`</summary>
716
717 ```toml
718 [tool.black]
719 line-length = 88
720 target-version = ['py37']
721 include = '\.pyi?$'
722 exclude = '''
723
724 (
725   /(
726       \.eggs         # exclude a few common directories in the
727     | \.git          # root of the project
728     | \.hg
729     | \.mypy_cache
730     | \.tox
731     | \.venv
732     | _build
733     | buck-out
734     | build
735     | dist
736   )/
737   | foo.py           # also separately exclude a file named foo.py in
738                      # the root of the project
739 )
740 '''
741 ```
742
743 </details>
744
745 ### Lookup hierarchy
746
747 Command-line options have defaults that you can see in `--help`. A `pyproject.toml` can
748 override those defaults. Finally, options provided by the user on the command line
749 override both.
750
751 _Black_ will only ever use one `pyproject.toml` file during an entire run. It doesn't
752 look for multiple files, and doesn't compose configuration from different levels of the
753 file hierarchy.
754
755 ## Editor integration
756
757 ### Emacs
758
759 Options include the following:
760
761 - [purcell/reformatter.el](https://github.com/purcell/reformatter.el)
762 - [proofit404/blacken](https://github.com/proofit404/blacken)
763 - [Elpy](https://github.com/jorgenschaefer/elpy).
764
765 ### PyCharm/IntelliJ IDEA
766
767 1. Install `black`.
768
769 ```console
770 $ pip install black
771 ```
772
773 2. Locate your `black` installation folder.
774
775 On macOS / Linux / BSD:
776
777 ```console
778 $ which black
779 /usr/local/bin/black  # possible location
780 ```
781
782 On Windows:
783
784 ```console
785 $ where black
786 %LocalAppData%\Programs\Python\Python36-32\Scripts\black.exe  # possible location
787 ```
788
789 Note that if you are using a virtual environment detected by PyCharm, this is an
790 unneeded step. In this case the path to `black` is `$PyInterpreterDirectory$/black`.
791
792 3. Open External tools in PyCharm/IntelliJ IDEA
793
794 On macOS:
795
796 `PyCharm -> Preferences -> Tools -> External Tools`
797
798 On Windows / Linux / BSD:
799
800 `File -> Settings -> Tools -> External Tools`
801
802 4. Click the + icon to add a new external tool with the following values:
803
804    - Name: Black
805    - Description: Black is the uncompromising Python code formatter.
806    - Program: <install_location_from_step_2>
807    - Arguments: `"$FilePath$"`
808
809 5. Format the currently opened file by selecting `Tools -> External Tools -> black`.
810
811    - Alternatively, you can set a keyboard shortcut by navigating to
812      `Preferences or Settings -> Keymap -> External Tools -> External Tools - Black`.
813
814 6. Optionally, run _Black_ on every file save:
815
816    1. Make sure you have the
817       [File Watchers](https://plugins.jetbrains.com/plugin/7177-file-watchers) plugin
818       installed.
819    2. Go to `Preferences or Settings -> Tools -> File Watchers` and click `+` to add a
820       new watcher:
821       - Name: Black
822       - File type: Python
823       - Scope: Project Files
824       - Program: <install_location_from_step_2>
825       - Arguments: `$FilePath$`
826       - Output paths to refresh: `$FilePath$`
827       - Working directory: `$ProjectFileDir$`
828
829    - Uncheck "Auto-save edited files to trigger the watcher" in Advanced Options
830
831 ### Wing IDE
832
833 Wing supports black via the OS Commands tool, as explained in the Wing documentation on
834 [pep8 formatting](https://wingware.com/doc/edit/pep8). The detailed procedure is:
835
836 1. Install `black`.
837
838 ```console
839 $ pip install black
840 ```
841
842 2. Make sure it runs from the command line, e.g.
843
844 ```console
845 $ black --help
846 ```
847
848 3. In Wing IDE, activate the **OS Commands** panel and define the command **black** to
849    execute black on the currently selected file:
850
851 - Use the Tools -> OS Commands menu selection
852 - click on **+** in **OS Commands** -> New: Command line..
853   - Title: black
854   - Command Line: black %s
855   - I/O Encoding: Use Default
856   - Key Binding: F1
857   - [x] Raise OS Commands when executed
858   - [x] Auto-save files before execution
859   - [x] Line mode
860
861 4. Select a file in the editor and press **F1** , or whatever key binding you selected
862    in step 3, to reformat the file.
863
864 ### Vim
865
866 Commands and shortcuts:
867
868 - `:Black` to format the entire file (ranges not supported);
869 - `:BlackUpgrade` to upgrade _Black_ inside the virtualenv;
870 - `:BlackVersion` to get the current version of _Black_ inside the virtualenv.
871
872 Configuration:
873
874 - `g:black_fast` (defaults to `0`)
875 - `g:black_linelength` (defaults to `88`)
876 - `g:black_skip_string_normalization` (defaults to `0`)
877 - `g:black_virtualenv` (defaults to `~/.vim/black` or `~/.local/share/nvim/black`)
878
879 To install with [vim-plug](https://github.com/junegunn/vim-plug):
880
881 ```
882 Plug 'psf/black', { 'branch': 'stable' }
883 ```
884
885 or with [Vundle](https://github.com/VundleVim/Vundle.vim):
886
887 ```
888 Plugin 'psf/black'
889 ```
890
891 and execute the following in a terminal:
892
893 ```console
894 $ cd ~/.vim/bundle/black
895 $ git checkout origin/stable -b stable
896 ```
897
898 or you can copy the plugin from
899 [plugin/black.vim](https://github.com/psf/black/blob/stable/plugin/black.vim).
900
901 ```
902 mkdir -p ~/.vim/pack/python/start/black/plugin
903 curl https://raw.githubusercontent.com/psf/black/master/plugin/black.vim -o ~/.vim/pack/python/start/black/plugin/black.vim
904 ```
905
906 Let me know if this requires any changes to work with Vim 8's builtin `packadd`, or
907 Pathogen, and so on.
908
909 This plugin **requires Vim 7.0+ built with Python 3.6+ support**. It needs Python 3.6 to
910 be able to run _Black_ inside the Vim process which is much faster than calling an
911 external command.
912
913 On first run, the plugin creates its own virtualenv using the right Python version and
914 automatically installs _Black_. You can upgrade it later by calling `:BlackUpgrade` and
915 restarting Vim.
916
917 If you need to do anything special to make your virtualenv work and install _Black_ (for
918 example you want to run a version from master), create a virtualenv manually and point
919 `g:black_virtualenv` to it. The plugin will use it.
920
921 To run _Black_ on save, add the following line to `.vimrc` or `init.vim`:
922
923 ```
924 autocmd BufWritePre *.py execute ':Black'
925 ```
926
927 To run _Black_ on a key press (e.g. F9 below), add this:
928
929 ```
930 nnoremap <F9> :Black<CR>
931 ```
932
933 **How to get Vim with Python 3.6?** On Ubuntu 17.10 Vim comes with Python 3.6 by
934 default. On macOS with Homebrew run: `brew install vim`. When building Vim from source,
935 use: `./configure --enable-python3interp=yes`. There's many guides online how to do
936 this.
937
938 **I get an import error when using _Black_ from a virtual environment**: If you get an
939 error message like this:
940
941 ```text
942 Traceback (most recent call last):
943   File "<string>", line 63, in <module>
944   File "/home/gui/.vim/black/lib/python3.7/site-packages/black.py", line 45, in <module>
945     from typed_ast import ast3, ast27
946   File "/home/gui/.vim/black/lib/python3.7/site-packages/typed_ast/ast3.py", line 40, in <module>
947     from typed_ast import _ast3
948 ImportError: /home/gui/.vim/black/lib/python3.7/site-packages/typed_ast/_ast3.cpython-37m-x86_64-linux-gnu.so: undefined symbool: PyExc_KeyboardInterrupt
949 ```
950
951 Then you need to install `typed_ast` and `regex` directly from the source code. The
952 error happens because `pip` will download [Python wheels](https://pythonwheels.com/) if
953 they are available. Python wheels are a new standard of distributing Python packages and
954 packages that have Cython and extensions written in C are already compiled, so the
955 installation is much more faster. The problem here is that somehow the Python
956 environment inside Vim does not match with those already compiled C extensions and these
957 kind of errors are the result. Luckily there is an easy fix: installing the packages
958 from the source code.
959
960 The two packages that cause the problem are:
961
962 - [regex](https://pypi.org/project/regex/)
963 - [typed-ast](https://pypi.org/project/typed-ast/)
964
965 Now remove those two packages:
966
967 ```console
968 $ pip uninstall regex typed-ast -y
969 ```
970
971 And now you can install them with:
972
973 ```console
974 $ pip install --no-binary :all: regex typed-ast
975 ```
976
977 The C extensions will be compiled and now Vim's Python environment will match. Note that
978 you need to have the GCC compiler and the Python development files installed (on
979 Ubuntu/Debian do `sudo apt-get install build-essential python3-dev`).
980
981 If you later want to update _Black_, you should do it like this:
982
983 ```console
984 $ pip install -U black --no-binary regex,typed-ast
985 ```
986
987 ### Visual Studio Code
988
989 Use the
990 [Python extension](https://marketplace.visualstudio.com/items?itemName=ms-python.python)
991 ([instructions](https://code.visualstudio.com/docs/python/editing#_formatting)).
992
993 ### SublimeText 3
994
995 Use [sublack plugin](https://github.com/jgirardet/sublack).
996
997 ### Jupyter Notebook Magic
998
999 Use [blackcellmagic](https://github.com/csurfer/blackcellmagic).
1000
1001 ### Python Language Server
1002
1003 If your editor supports the [Language Server Protocol](https://langserver.org/) (Atom,
1004 Sublime Text, Visual Studio Code and many more), you can use the
1005 [Python Language Server](https://github.com/palantir/python-language-server) with the
1006 [pyls-black](https://github.com/rupert/pyls-black) plugin.
1007
1008 ### Atom/Nuclide
1009
1010 Use [python-black](https://atom.io/packages/python-black).
1011
1012 ### Kakoune
1013
1014 Add the following hook to your kakrc, then run _Black_ with `:format`.
1015
1016 ```
1017 hook global WinSetOption filetype=python %{
1018     set-option window formatcmd 'black -q  -'
1019 }
1020 ```
1021
1022 ### Thonny
1023
1024 Use [Thonny-black-code-format](https://github.com/Franccisco/thonny-black-code-format).
1025
1026 ### Other editors
1027
1028 Other editors will require external contributions.
1029
1030 Patches welcome! ✨ 🍰 ✨
1031
1032 Any tool that can pipe code through _Black_ using its stdio mode (just
1033 [use `-` as the file name](https://www.tldp.org/LDP/abs/html/special-chars.html#DASHREF2)).
1034 The formatted code will be returned on stdout (unless `--check` was passed). _Black_
1035 will still emit messages on stderr but that shouldn't affect your use case.
1036
1037 This can be used for example with PyCharm's or IntelliJ's
1038 [File Watchers](https://www.jetbrains.com/help/pycharm/file-watchers.html).
1039
1040 ## blackd
1041
1042 `blackd` is a small HTTP server that exposes _Black_'s functionality over a simple
1043 protocol. The main benefit of using it is to avoid paying the cost of starting up a new
1044 _Black_ process every time you want to blacken a file.
1045
1046 ### Usage
1047
1048 `blackd` is not packaged alongside _Black_ by default because it has additional
1049 dependencies. You will need to do `pip install black[d]` to install it.
1050
1051 You can start the server on the default port, binding only to the local interface by
1052 running `blackd`. You will see a single line mentioning the server's version, and the
1053 host and port it's listening on. `blackd` will then print an access log similar to most
1054 web servers on standard output, merged with any exception traces caused by invalid
1055 formatting requests.
1056
1057 `blackd` provides even less options than _Black_. You can see them by running
1058 `blackd --help`:
1059
1060 ```text
1061 Usage: blackd [OPTIONS]
1062
1063 Options:
1064   --bind-host TEXT                Address to bind the server to.
1065   --bind-port INTEGER             Port to listen on
1066   --version                       Show the version and exit.
1067   -h, --help                      Show this message and exit.
1068 ```
1069
1070 There is no official blackd client tool (yet!). You can test that blackd is working
1071 using `curl`:
1072
1073 ```sh
1074 blackd --bind-port 9090 &  # or let blackd choose a port
1075 curl -s -XPOST "localhost:9090" -d "print('valid')"
1076 ```
1077
1078 ### Protocol
1079
1080 `blackd` only accepts `POST` requests at the `/` path. The body of the request should
1081 contain the python source code to be formatted, encoded according to the `charset` field
1082 in the `Content-Type` request header. If no `charset` is specified, `blackd` assumes
1083 `UTF-8`.
1084
1085 There are a few HTTP headers that control how the source is formatted. These correspond
1086 to command line flags for _Black_. There is one exception to this: `X-Protocol-Version`
1087 which if present, should have the value `1`, otherwise the request is rejected with
1088 `HTTP 501` (Not Implemented).
1089
1090 The headers controlling how code is formatted are:
1091
1092 - `X-Line-Length`: corresponds to the `--line-length` command line flag.
1093 - `X-Skip-String-Normalization`: corresponds to the `--skip-string-normalization`
1094   command line flag. If present and its value is not the empty string, no string
1095   normalization will be performed.
1096 - `X-Fast-Or-Safe`: if set to `fast`, `blackd` will act as _Black_ does when passed the
1097   `--fast` command line flag.
1098 - `X-Python-Variant`: if set to `pyi`, `blackd` will act as _Black_ does when passed the
1099   `--pyi` command line flag. Otherwise, its value must correspond to a Python version or
1100   a set of comma-separated Python versions, optionally prefixed with `py`. For example,
1101   to request code that is compatible with Python 3.5 and 3.6, set the header to
1102   `py3.5,py3.6`.
1103 - `X-Diff`: corresponds to the `--diff` command line flag. If present, a diff of the
1104   formats will be output.
1105
1106 If any of these headers are set to invalid values, `blackd` returns a `HTTP 400` error
1107 response, mentioning the name of the problematic header in the message body.
1108
1109 Apart from the above, `blackd` can produce the following response codes:
1110
1111 - `HTTP 204`: If the input is already well-formatted. The response body is empty.
1112 - `HTTP 200`: If formatting was needed on the input. The response body contains the
1113   blackened Python code, and the `Content-Type` header is set accordingly.
1114 - `HTTP 400`: If the input contains a syntax error. Details of the error are returned in
1115   the response body.
1116 - `HTTP 500`: If there was any kind of error while trying to format the input. The
1117   response body contains a textual representation of the error.
1118
1119 The response headers include a `X-Black-Version` header containing the version of
1120 _Black_.
1121
1122 ## black-primer
1123
1124 `black-primer` is a tool built for CI (and huumans) to have _Black_ `--check` a number
1125 of (configured in `primer.json`) Git accessible projects in parallel. _(A PR will be
1126 accepted to add Mercurial support.)_
1127
1128 ### Run flow
1129
1130 - Ensure we have a `black` + `git` in PATH
1131 - Load projects from `primer.json`
1132 - Run projects in parallel with `--worker` workers (defaults to CPU count / 2)
1133   - Checkout projects
1134   - Run black and record result
1135   - Clean up repository checkout _(can optionally be disabled via `--keep`)_
1136 - Display results summary to screen
1137 - Default to cleaning up `--work-dir` (which defaults to tempfile schemantics)
1138 - Return
1139   - 0 for successful run
1140   - < 0 for environment / internal error
1141   - > 0 for each project with an error
1142
1143 ### Speed up Runs 🏎
1144
1145 If you're running locally yourself to test black on lots of code try:
1146
1147 - Using `-k` / `--keep` + `-w` / `--work-dir` so you don't have to re-checkout the repo
1148   each run
1149
1150 ### CLI Arguments
1151
1152 ```text
1153 Usage: black-primer [OPTIONS]
1154
1155   primer - prime projects for blackening... 🏴
1156
1157 Options:
1158   -c, --config PATH      JSON config file path  [default: /Users/cooper/repos/
1159                          black/src/black_primer/primer.json]
1160
1161   --debug                Turn on debug logging  [default: False]
1162   -k, --keep             Keep workdir + repos post run  [default: False]
1163   -L, --long-checkouts   Pull big projects to test  [default: False]
1164   -R, --rebase           Rebase project if already checked out  [default:
1165                          False]
1166
1167   -w, --workdir PATH     Directory Path for repo checkouts  [default: /var/fol
1168                          ders/tc/hbwxh76j1hn6gqjd2n2sjn4j9k1glp/T/primer.20200
1169                          517125229]
1170
1171   -W, --workers INTEGER  Number of parallel worker coroutines  [default: 69]
1172   -h, --help             Show this message and exit.
1173 ```
1174
1175 ### primer config file
1176
1177 The config is JSON format. Its main element is the `"projects"` dictionary. Below
1178 explains each parameter:
1179
1180 ```json
1181 {
1182   "projects": {
1183     "00_Example": {
1184       "cli_arguments": "List of extra CLI arguments to pass Black for this project",
1185       "expect_formatting_changes": "Boolean to indicate that the version of Black is expected to cause changes",
1186       "git_clone_url": "URL you would pass `git clone` to check out this repo",
1187       "long_checkout": "Boolean to have repo skipped by defauult unless `--long-checkouts` is specified",
1188       "py_versions": "List of major Python versions to run this project with - all will do as you'd expect - run on ALL versions"
1189     },
1190     "aioexabgp": {
1191       "cli_arguments": [],
1192       "expect_formatting_changes": true,
1193       "git_clone_url": "https://github.com/cooperlees/aioexabgp.git",
1194       "long_checkout": false,
1195       "py_versions": ["all", "3.8"] // "all" ignores all other versions
1196     }
1197   }
1198 }
1199 ```
1200
1201 ### Example run
1202
1203 ```console
1204 cooper-mbp:black cooper$ ~/venvs/b/bin/black-primer
1205 [2020-05-17 13:06:40,830] INFO: 4 projects to run Black over (lib.py:270)
1206 [2020-05-17 13:06:44,215] INFO: Analyzing results (lib.py:285)
1207 -- primer results 📊 --
1208
1209 3 / 4 succeeded (75.0%) ✅
1210 1 / 4 FAILED (25.0%) 💩
1211  - 0 projects disabled by config
1212  - 0 projects skipped due to Python version
1213  - 0 skipped due to long checkout
1214
1215 Failed projects:
1216
1217 ## flake8-bugbear:
1218  - Returned 1
1219  - stdout:
1220 --- tests/b303_b304.py  2020-05-17 20:04:09.991227 +0000
1221 +++ tests/b303_b304.py  2020-05-17 20:06:42.753851 +0000
1222 @@ -26,11 +26,11 @@
1223      maxint = 5  # this is okay
1224      # the following shouldn't crash
1225      (a, b, c) = list(range(3))
1226      # it's different than this
1227      a, b, c = list(range(3))
1228 -    a, b, c, = list(range(3))
1229 +    a, b, c = list(range(3))
1230      # and different than this
1231      (a, b), c = list(range(3))
1232      a, *b, c = [1, 2, 3, 4, 5]
1233      b[1:3] = [0, 0]
1234
1235 would reformat tests/b303_b304.py
1236 Oh no! 💥 💔 💥
1237 1 file would be reformatted, 22 files would be left unchanged.
1238 ```
1239
1240 ## Version control integration
1241
1242 Use [pre-commit](https://pre-commit.com/). Once you
1243 [have it installed](https://pre-commit.com/#install), add this to the
1244 `.pre-commit-config.yaml` in your repository:
1245
1246 ```yaml
1247 repos:
1248   - repo: https://github.com/psf/black
1249     rev: stable
1250     hooks:
1251       - id: black
1252         language_version: python3.6
1253 ```
1254
1255 Then run `pre-commit install` and you're ready to go.
1256
1257 Avoid using `args` in the hook. Instead, store necessary configuration in
1258 `pyproject.toml` so that editors and command-line usage of Black all behave consistently
1259 for your project. See _Black_'s own
1260 [pyproject.toml](https://github.com/psf/black/blob/master/pyproject.toml) for an
1261 example.
1262
1263 If you're already using Python 3.7, switch the `language_version` accordingly. Finally,
1264 `stable` is a branch that tracks the latest release on PyPI. If you'd rather run on
1265 master, this is also an option.
1266
1267 ## Ignoring unmodified files
1268
1269 _Black_ remembers files it has already formatted, unless the `--diff` flag is used or
1270 code is passed via standard input. This information is stored per-user. The exact
1271 location of the file depends on the _Black_ version and the system on which _Black_ is
1272 run. The file is non-portable. The standard location on common operating systems is:
1273
1274 - Windows:
1275   `C:\\Users\<username>\AppData\Local\black\black\Cache\<version>\cache.<line-length>.<file-mode>.pickle`
1276 - macOS:
1277   `/Users/<username>/Library/Caches/black/<version>/cache.<line-length>.<file-mode>.pickle`
1278 - Linux:
1279   `/home/<username>/.cache/black/<version>/cache.<line-length>.<file-mode>.pickle`
1280
1281 `file-mode` is an int flag that determines whether the file was formatted as 3.6+ only,
1282 as .pyi, and whether string normalization was omitted.
1283
1284 To override the location of these files on macOS or Linux, set the environment variable
1285 `XDG_CACHE_HOME` to your preferred location. For example, if you want to put the cache
1286 in the directory you're running _Black_ from, set `XDG_CACHE_HOME=.cache`. _Black_ will
1287 then write the above files to `.cache/black/<version>/`.
1288
1289 ## Used by
1290
1291 The following notable open-source projects trust _Black_ with enforcing a consistent
1292 code style: pytest, tox, Pyramid, Django Channels, Hypothesis, attrs, SQLAlchemy,
1293 Poetry, PyPA applications (Warehouse, Bandersnatch, Pipenv, virtualenv), pandas, Pillow,
1294 every Datadog Agent Integration, Home Assistant.
1295
1296 The following organizations use _Black_: Facebook, Dropbox.
1297
1298 Are we missing anyone? Let us know.
1299
1300 ## Testimonials
1301
1302 **Dusty Phillips**,
1303 [writer](https://smile.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=dusty+phillips):
1304
1305 > _Black_ is opinionated so you don't have to be.
1306
1307 **Hynek Schlawack**, [creator of `attrs`](https://www.attrs.org/), core developer of
1308 Twisted and CPython:
1309
1310 > An auto-formatter that doesn't suck is all I want for Xmas!
1311
1312 **Carl Meyer**, [Django](https://www.djangoproject.com/) core developer:
1313
1314 > At least the name is good.
1315
1316 **Kenneth Reitz**, creator of [`requests`](http://python-requests.org/) and
1317 [`pipenv`](https://docs.pipenv.org/):
1318
1319 > This vastly improves the formatting of our code. Thanks a ton!
1320
1321 ## Show your style
1322
1323 Use the badge in your project's README.md:
1324
1325 ```markdown
1326 [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
1327 ```
1328
1329 Using the badge in README.rst:
1330
1331 ```
1332 .. image:: https://img.shields.io/badge/code%20style-black-000000.svg
1333     :target: https://github.com/psf/black
1334 ```
1335
1336 Looks like this:
1337 [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
1338
1339 ## License
1340
1341 MIT
1342
1343 ## Contributing to _Black_
1344
1345 In terms of inspiration, _Black_ is about as configurable as _gofmt_. This is
1346 deliberate.
1347
1348 Bug reports and fixes are always welcome! However, before you suggest a new feature or
1349 configuration knob, ask yourself why you want it. If it enables better integration with
1350 some workflow, fixes an inconsistency, speeds things up, and so on - go for it! On the
1351 other hand, if your answer is "because I don't like a particular formatting" then you're
1352 not ready to embrace _Black_ yet. Such changes are unlikely to get accepted. You can
1353 still try but prepare to be disappointed.
1354
1355 More details can be found in
1356 [CONTRIBUTING](https://github.com/psf/black/blob/master/CONTRIBUTING.md).
1357
1358 ## Change Log
1359
1360 The log's become rather long. It moved to its own file.
1361
1362 See [CHANGES](https://github.com/psf/black/blob/master/CHANGES.md).
1363
1364 ## Authors
1365
1366 Glued together by [Łukasz Langa](mailto:lukasz@langa.pl).
1367
1368 Maintained with [Carol Willing](mailto:carolcode@willingconsulting.com),
1369 [Carl Meyer](mailto:carl@oddbird.net),
1370 [Jelle Zijlstra](mailto:jelle.zijlstra@gmail.com),
1371 [Mika Naylor](mailto:mail@autophagy.io),
1372 [Zsolt Dollenstein](mailto:zsol.zsol@gmail.com), and
1373 [Cooper Lees](mailto:me@cooperlees.com).
1374
1375 Multiple contributions by:
1376
1377 - [Abdur-Rahmaan Janhangeer](mailto:arj.python@gmail.com)
1378 - [Adam Johnson](mailto:me@adamj.eu)
1379 - [Alexander Huynh](mailto:github@grande.coffee)
1380 - [Andrew Thorp](mailto:andrew.thorp.dev@gmail.com)
1381 - [Andrey](mailto:dyuuus@yandex.ru)
1382 - [Andy Freeland](mailto:andy@andyfreeland.net)
1383 - [Anthony Sottile](mailto:asottile@umich.edu)
1384 - [Arjaan Buijk](mailto:arjaan.buijk@gmail.com)
1385 - [Artem Malyshev](mailto:proofit404@gmail.com)
1386 - [Asger Hautop Drewsen](mailto:asgerdrewsen@gmail.com)
1387 - [Augie Fackler](mailto:raf@durin42.com)
1388 - [Aviskar KC](mailto:aviskarkc10@gmail.com)
1389 - [Benjamin Woodruff](mailto:github@benjam.info)
1390 - [Brandt Bucher](mailto:brandtbucher@gmail.com)
1391 - Charles Reid
1392 - [Christian Heimes](mailto:christian@python.org)
1393 - [Chuck Wooters](mailto:chuck.wooters@microsoft.com)
1394 - [Cooper Ry Lees](mailto:me@cooperlees.com)
1395 - [Daniel Hahler](mailto:github@thequod.de)
1396 - [Daniel M. Capella](mailto:polycitizen@gmail.com)
1397 - Daniele Esposti
1398 - dylanjblack
1399 - [Eli Treuherz](mailto:eli@treuherz.com)
1400 - [Florent Thiery](mailto:fthiery@gmail.com)
1401 - hauntsaninja
1402 - Hugo van Kemenade
1403 - [Ivan Katanić](mailto:ivan.katanic@gmail.com)
1404 - [Jason Fried](mailto:me@jasonfried.info)
1405 - [jgirardet](mailto:ijkl@netc.fr)
1406 - [Joe Antonakakis](mailto:jma353@cornell.edu)
1407 - [Jon Dufresne](mailto:jon.dufresne@gmail.com)
1408 - [Jonas Obrist](mailto:ojiidotch@gmail.com)
1409 - [Josh Bode](mailto:joshbode@fastmail.com)
1410 - [Juan Luis Cano Rodríguez](mailto:hello@juanlu.space)
1411 - [Katie McLaughlin](mailto:katie@glasnt.com)
1412 - Lawrence Chan
1413 - [Linus Groh](mailto:mail@linusgroh.de)
1414 - [Luka Sterbic](mailto:luka.sterbic@gmail.com)
1415 - Mariatta
1416 - [Matt VanEseltine](mailto:vaneseltine@gmail.com)
1417 - [Michael Flaxman](mailto:michael.flaxman@gmail.com)
1418 - [Michael J. Sullivan](mailto:sully@msully.net)
1419 - [Michael McClimon](mailto:michael@mcclimon.org)
1420 - [Miguel Gaiowski](mailto:miggaiowski@gmail.com)
1421 - [Mike](mailto:roshi@fedoraproject.org)
1422 - [Min ho Kim](mailto:minho42@gmail.com)
1423 - [Miroslav Shubernetskiy](mailto:miroslav@miki725.com)
1424 - [Neraste](mailto:neraste.herr10@gmail.com)
1425 - [Ofek Lev](mailto:ofekmeister@gmail.com)
1426 - [Osaetin Daniel](mailto:osaetindaniel@gmail.com)
1427 - [Pablo Galindo](mailto:Pablogsal@gmail.com)
1428 - [Peter Bengtsson](mailto:mail@peterbe.com)
1429 - pmacosta
1430 - [Rishikesh Jha](mailto:rishijha424@gmail.com)
1431 - [Stavros Korokithakis](mailto:hi@stavros.io)
1432 - [Stephen Rosen](mailto:sirosen@globus.org)
1433 - [Sunil Kapil](mailto:snlkapil@gmail.com)
1434 - [Thom Lu](mailto:thomas.c.lu@gmail.com)
1435 - [Tom Christie](mailto:tom@tomchristie.com)
1436 - [Tzu-ping Chung](mailto:uranusjr@gmail.com)
1437 - [Utsav Shah](mailto:ukshah2@illinois.edu)
1438 - vezeli
1439 - [Vishwas B Sharma](mailto:sharma.vishwas88@gmail.com)
1440 - [Yngve Høiseth](mailto:yngve@hoiseth.net)
1441 - [Yurii Karabas](mailto:1998uriyyo@gmail.com)