]> git.madduck.net Git - etc/vim.git/blob - .vim/bundle/black/docs/usage_and_configuration/the_basics.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:

Merge commit '882d8795c6ff65c02f2657e596391748d1b6b7f5'
[etc/vim.git] / .vim / bundle / black / docs / usage_and_configuration / the_basics.md
1 # The basics
2
3 Foundational knowledge on using and configuring Black.
4
5 _Black_ is a well-behaved Unix-style command-line tool:
6
7 - it does nothing if it finds no sources to format;
8 - it will read from standard input and write to standard output if `-` is used as the
9   filename;
10 - it only outputs messages to users on standard error;
11 - exits with code 0 unless an internal error occurred or a CLI option prompted it.
12
13 ## Usage
14
15 To get started right away with sensible defaults:
16
17 ```sh
18 black {source_file_or_directory}
19 ```
20
21 You can run _Black_ as a package if running it as a script doesn't work:
22
23 ```sh
24 python -m black {source_file_or_directory}
25 ```
26
27 ### Command line options
28
29 The CLI options of _Black_ can be displayed by running `black --help`. All options are
30 also covered in more detail below.
31
32 While _Black_ has quite a few knobs these days, it is still opinionated so style options
33 are deliberately limited and rarely added.
34
35 Note that all command-line options listed above can also be configured using a
36 `pyproject.toml` file (more on that below).
37
38 #### `-c`, `--code`
39
40 Format the code passed in as a string.
41
42 ```console
43 $ black --code "print ( 'hello, world' )"
44 print("hello, world")
45 ```
46
47 #### `-l`, `--line-length`
48
49 How many characters per line to allow. The default is 88.
50
51 See also [the style documentation](labels/line-length).
52
53 #### `-t`, `--target-version`
54
55 Python versions that should be supported by Black's output. You can run `black --help`
56 and look for the `--target-version` option to see the full list of supported versions.
57 You should include all versions that your code supports. If you support Python 3.8
58 through 3.11, you should write:
59
60 ```console
61 $ black -t py38 -t py39 -t py310 -t py311
62 ```
63
64 In a [configuration file](#configuration-via-a-file), you can write:
65
66 ```toml
67 target-version = ["py38", "py39", "py310", "py311"]
68 ```
69
70 _Black_ uses this option to decide what grammar to use to parse your code. In addition,
71 it may use it to decide what style to use. For example, support for a trailing comma
72 after `*args` in a function call was added in Python 3.5, so _Black_ will add this comma
73 only if the target versions are all Python 3.5 or higher:
74
75 ```console
76 $ black --line-length=10 --target-version=py35 -c 'f(a, *args)'
77 f(
78     a,
79     *args,
80 )
81 $ black --line-length=10 --target-version=py34 -c 'f(a, *args)'
82 f(
83     a,
84     *args
85 )
86 $ black --line-length=10 --target-version=py34 --target-version=py35 -c 'f(a, *args)'
87 f(
88     a,
89     *args
90 )
91 ```
92
93 #### `--pyi`
94
95 Format all input files like typing stubs regardless of file extension. This is useful
96 when piping source on standard input.
97
98 #### `--ipynb`
99
100 Format all input files like Jupyter Notebooks regardless of file extension. This is
101 useful when piping source on standard input.
102
103 #### `--python-cell-magics`
104
105 When processing Jupyter Notebooks, add the given magic to the list of known python-
106 magics. Useful for formatting cells with custom python magics.
107
108 #### `-S, --skip-string-normalization`
109
110 By default, _Black_ uses double quotes for all strings and normalizes string prefixes,
111 as described in [the style documentation](labels/strings). If this option is given,
112 strings are left unchanged instead.
113
114 #### `-C, --skip-magic-trailing-comma`
115
116 By default, _Black_ uses existing trailing commas as an indication that short lines
117 should be left separate, as described in
118 [the style documentation](labels/magic-trailing-comma). If this option is given, the
119 magic trailing comma is ignored.
120
121 #### `--preview`
122
123 Enable potentially disruptive style changes that may be added to Black's main
124 functionality in the next major release. Read more about
125 [our preview style](labels/preview-style).
126
127 (labels/exit-code)=
128
129 #### `--check`
130
131 Passing `--check` will make _Black_ exit with:
132
133 - code 0 if nothing would change;
134 - code 1 if some files would be reformatted; or
135 - code 123 if there was an internal error
136
137 ```console
138 $ black test.py --check
139 All done! ✨ 🍰 ✨
140 1 file would be left unchanged.
141 $ echo $?
142 0
143
144 $ black test.py --check
145 would reformat test.py
146 Oh no! 💥 💔 💥
147 1 file would be reformatted.
148 $ echo $?
149 1
150
151 $ black test.py --check
152 error: cannot format test.py: INTERNAL ERROR: Black produced code that is not equivalent to the source.  Please report a bug on https://github.com/psf/black/issues.  This diff might be helpful: /tmp/blk_kjdr1oog.log
153 Oh no! 💥 💔 💥
154 1 file would fail to reformat.
155 $ echo $?
156 123
157 ```
158
159 #### `--diff`
160
161 Passing `--diff` will make _Black_ print out diffs that indicate what changes _Black_
162 would've made. They are printed to stdout so capturing them is simple.
163
164 If you'd like colored diffs, you can enable them with `--color`.
165
166 ```console
167 $ black test.py --diff
168 --- test.py     2021-03-08 22:23:40.848954+00:00
169 +++ test.py     2021-03-08 22:23:47.126319+00:00
170 @@ -1 +1 @@
171 -print ( 'hello, world' )
172 +print("hello, world")
173 would reformat test.py
174 All done! ✨ 🍰 ✨
175 1 file would be reformatted.
176 ```
177
178 #### `--color` / `--no-color`
179
180 Show (or do not show) colored diff. Only applies when `--diff` is given.
181
182 #### `--fast` / `--safe`
183
184 By default, _Black_ performs [an AST safety check](labels/ast-changes) after formatting
185 your code. The `--fast` flag turns off this check and the `--safe` flag explicitly
186 enables it.
187
188 #### `--required-version`
189
190 Require a specific version of _Black_ to be running. This is useful for ensuring that
191 all contributors to your project are using the same version, because different versions
192 of _Black_ may format code a little differently. This option can be set in a
193 configuration file for consistent results across environments.
194
195 ```console
196 $ black --version
197 black, 23.10.0 (compiled: yes)
198 $ black --required-version 23.10.0 -c "format = 'this'"
199 format = "this"
200 $ black --required-version 31.5b2 -c "still = 'beta?!'"
201 Oh no! 💥 💔 💥 The required version does not match the running version!
202 ```
203
204 You can also pass just the major version:
205
206 ```console
207 $ black --required-version 22 -c "format = 'this'"
208 format = "this"
209 $ black --required-version 31 -c "still = 'beta?!'"
210 Oh no! 💥 💔 💥 The required version does not match the running version!
211 ```
212
213 Because of our [stability policy](../the_black_code_style/index.md), this will guarantee
214 stable formatting, but still allow you to take advantage of improvements that do not
215 affect formatting.
216
217 #### `--include`
218
219 A regular expression that matches files and directories that should be included on
220 recursive searches. An empty value means all files are included regardless of the name.
221 Use forward slashes for directories on all platforms (Windows, too). Exclusions are
222 calculated first, inclusions later.
223
224 #### `--exclude`
225
226 A regular expression that matches files and directories that should be excluded on
227 recursive searches. An empty value means no paths are excluded. Use forward slashes for
228 directories on all platforms (Windows, too). Exclusions are calculated first, inclusions
229 later.
230
231 #### `--extend-exclude`
232
233 Like `--exclude`, but adds additional files and directories on top of the excluded ones.
234 Useful if you simply want to add to the default.
235
236 #### `--force-exclude`
237
238 Like `--exclude`, but files and directories matching this regex will be excluded even
239 when they are passed explicitly as arguments. This is useful when invoking _Black_
240 programmatically on changed files, such as in a pre-commit hook or editor plugin.
241
242 #### `--stdin-filename`
243
244 The name of the file when passing it through stdin. Useful to make sure Black will
245 respect the `--force-exclude` option on some editors that rely on using stdin.
246
247 #### `-W`, `--workers`
248
249 When _Black_ formats multiple files, it may use a process pool to speed up formatting.
250 This option controls the number of parallel workers. This can also be specified via the
251 `BLACK_NUM_WORKERS` environment variable.
252
253 #### `-q`, `--quiet`
254
255 Passing `-q` / `--quiet` will cause _Black_ to stop emitting all non-critical output.
256 Error messages will still be emitted (which can silenced by `2>/dev/null`).
257
258 ```console
259 $ black src/ -q
260 error: cannot format src/black_primer/cli.py: Cannot parse: 5:6: mport asyncio
261 ```
262
263 #### `-v`, `--verbose`
264
265 Passing `-v` / `--verbose` will cause _Black_ to also emit messages about files that
266 were not changed or were ignored due to exclusion patterns. If _Black_ is using a
267 configuration file, a blue message detailing which one it is using will be emitted.
268
269 ```console
270 $ black src/ -v
271 Using configuration from /tmp/pyproject.toml.
272 src/blib2to3 ignored: matches the --extend-exclude regular expression
273 src/_black_version.py wasn't modified on disk since last run.
274 src/black/__main__.py wasn't modified on disk since last run.
275 error: cannot format src/black_primer/cli.py: Cannot parse: 5:6: mport asyncio
276 reformatted src/black_primer/lib.py
277 reformatted src/blackd/__init__.py
278 reformatted src/black/__init__.py
279 Oh no! 💥 💔 💥
280 3 files reformatted, 2 files left unchanged, 1 file failed to reformat
281 ```
282
283 #### `--version`
284
285 You can check the version of _Black_ you have installed using the `--version` flag.
286
287 ```console
288 $ black --version
289 black, 23.10.0
290 ```
291
292 #### `--config`
293
294 Read configuration options from a configuration file. See
295 [below](#configuration-via-a-file) for more details on the configuration file.
296
297 #### `-h`, `--help`
298
299 Show available command-line options and exit.
300
301 ### Environment variable options
302
303 _Black_ supports the following configuration via environment variables.
304
305 #### `BLACK_CACHE_DIR`
306
307 The directory where _Black_ should store its cache.
308
309 #### `BLACK_NUM_WORKERS`
310
311 The number of parallel workers _Black_ should use. The command line option `-W` /
312 `--workers` takes precedence over this environment variable.
313
314 ### Code input alternatives
315
316 _Black_ supports formatting code via stdin, with the result being printed to stdout.
317 Just let _Black_ know with `-` as the path.
318
319 ```console
320 $ echo "print ( 'hello, world' )" | black -
321 print("hello, world")
322 reformatted -
323 All done! ✨ 🍰 ✨
324 1 file reformatted.
325 ```
326
327 **Tip:** if you need _Black_ to treat stdin input as a file passed directly via the CLI,
328 use `--stdin-filename`. Useful to make sure _Black_ will respect the `--force-exclude`
329 option on some editors that rely on using stdin.
330
331 You can also pass code as a string using the `-c` / `--code` option.
332
333 ### Writeback and reporting
334
335 By default _Black_ reformats the files given and/or found in place. Sometimes you need
336 _Black_ to just tell you what it _would_ do without actually rewriting the Python files.
337
338 There's two variations to this mode that are independently enabled by their respective
339 flags:
340
341 - `--check` (exit with code 1 if any file would be reformatted)
342 - `--diff` (print a diff instead of reformatting files)
343
344 Both variations can be enabled at once.
345
346 ### Output verbosity
347
348 _Black_ in general tries to produce the right amount of output, balancing between
349 usefulness and conciseness. By default, _Black_ emits files modified and error messages,
350 plus a short summary.
351
352 ```console
353 $ black src/
354 error: cannot format src/black_primer/cli.py: Cannot parse: 5:6: mport asyncio
355 reformatted src/black_primer/lib.py
356 reformatted src/blackd/__init__.py
357 reformatted src/black/__init__.py
358 Oh no! 💥 💔 💥
359 3 files reformatted, 2 files left unchanged, 1 file failed to reformat.
360 ```
361
362 The `--quiet` and `--verbose` flags control output verbosity.
363
364 ## Configuration via a file
365
366 _Black_ is able to read project-specific default values for its command line options
367 from a `pyproject.toml` file. This is especially useful for specifying custom
368 `--include` and `--exclude`/`--force-exclude`/`--extend-exclude` patterns for your
369 project.
370
371 **Pro-tip**: If you're asking yourself "Do I need to configure anything?" the answer is
372 "No". _Black_ is all about sensible defaults. Applying those defaults will have your
373 code in compliance with many other _Black_ formatted projects.
374
375 ### What on Earth is a `pyproject.toml` file?
376
377 [PEP 518](https://www.python.org/dev/peps/pep-0518/) defines `pyproject.toml` as a
378 configuration file to store build system requirements for Python projects. With the help
379 of tools like [Poetry](https://python-poetry.org/),
380 [Flit](https://flit.readthedocs.io/en/latest/), or
381 [Hatch](https://hatch.pypa.io/latest/) it can fully replace the need for `setup.py` and
382 `setup.cfg` files.
383
384 ### Where _Black_ looks for the file
385
386 By default _Black_ looks for `pyproject.toml` starting from the common base directory of
387 all files and directories passed on the command line. If it's not there, it looks in
388 parent directories. It stops looking when it finds the file, or a `.git` directory, or a
389 `.hg` directory, or the root of the file system, whichever comes first.
390
391 If you're formatting standard input, _Black_ will look for configuration starting from
392 the current working directory.
393
394 You can use a "global" configuration, stored in a specific location in your home
395 directory. This will be used as a fallback configuration, that is, it will be used if
396 and only if _Black_ doesn't find any configuration as mentioned above. Depending on your
397 operating system, this configuration file should be stored as:
398
399 - Windows: `~\.black`
400 - Unix-like (Linux, MacOS, etc.): `$XDG_CONFIG_HOME/black` (`~/.config/black` if the
401   `XDG_CONFIG_HOME` environment variable is not set)
402
403 Note that these are paths to the TOML file itself (meaning that they shouldn't be named
404 as `pyproject.toml`), not directories where you store the configuration. Here, `~`
405 refers to the path to your home directory. On Windows, this will be something like
406 `C:\\Users\UserName`.
407
408 You can also explicitly specify the path to a particular file that you want with
409 `--config`. In this situation _Black_ will not look for any other file.
410
411 If you're running with `--verbose`, you will see a blue message if a file was found and
412 used.
413
414 Please note `blackd` will not use `pyproject.toml` configuration.
415
416 ### Configuration format
417
418 As the file extension suggests, `pyproject.toml` is a
419 [TOML](https://github.com/toml-lang/toml) file. It contains separate sections for
420 different tools. _Black_ is using the `[tool.black]` section. The option keys are the
421 same as long names of options on the command line.
422
423 Note that you have to use single-quoted strings in TOML for regular expressions. It's
424 the equivalent of r-strings in Python. Multiline strings are treated as verbose regular
425 expressions by Black. Use `[ ]` to denote a significant space character.
426
427 <details>
428 <summary>Example <code>pyproject.toml</code></summary>
429
430 ```toml
431 [tool.black]
432 line-length = 88
433 target-version = ['py37']
434 include = '\.pyi?$'
435 # 'extend-exclude' excludes files or directories in addition to the defaults
436 extend-exclude = '''
437 # A regex preceded with ^/ will apply only to files and directories
438 # in the root of the project.
439 (
440   ^/foo.py    # exclude a file named foo.py in the root of the project
441   | .*_pb2.py  # exclude autogenerated Protocol Buffer files anywhere in the project
442 )
443 '''
444 ```
445
446 </details>
447
448 ### Lookup hierarchy
449
450 Command-line options have defaults that you can see in `--help`. A `pyproject.toml` can
451 override those defaults. Finally, options provided by the user on the command line
452 override both.
453
454 _Black_ will only ever use one `pyproject.toml` file during an entire run. It doesn't
455 look for multiple files, and doesn't compose configuration from different levels of the
456 file hierarchy.
457
458 ## Next steps
459
460 A good next step would be configuring auto-discovery so `black .` is all you need
461 instead of laborously listing every file or directory. You can get started by heading
462 over to [File collection and discovery](./file_collection_and_discovery.md).
463
464 Another good choice would be setting up an
465 [integration with your editor](../integrations/editors.md) of choice or with
466 [pre-commit for source version control](../integrations/source_version_control.md).