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