Debian Codegraph @

docs/usage_and_configuration/the_basics.md

raw
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 _Black_ will reformat entire files in place. To get started right away with sensible
16 defaults:
17
18 ```sh
19 black {source_file_or_directory}
20 ```
21
22 You can run _Black_ as a package if running it as a script doesn't work:
23
24 ```sh
25 python -m black {source_file_or_directory}
26 ```
27
28 ### Ignoring sections
29
30 Black will not reformat lines that contain `# fmt: skip` or blocks that start with
31 `# fmt: off` and end with `# fmt: on`. `# fmt: skip` can be mixed with other
32 pragmas/comments either with multiple comments (e.g. `# fmt: skip # pylint # noqa`) or
33 as a semicolon separated list (e.g. `# fmt: skip; pylint; noqa`). `# fmt: on/off` must
34 be on the same level of indentation and in the same block, meaning no unindents beyond
35 the initial indentation level between them. Black also recognizes
36 [YAPF](https://github.com/google/yapf)'s block comments to the same effect, as a
37 courtesy for straddling code.
38
39 ### Command line options
40
41 The CLI options of _Black_ can be displayed by running `black --help`. All options are
42 also covered in more detail below.
43
44 While _Black_ has quite a few knobs these days, it is still opinionated so style options
45 are deliberately limited and rarely added.
46
47 Note that all command-line options listed above can also be configured using a
48 `pyproject.toml` file (more on that below).
49
50 #### `-h`, `--help`
51
52 Show available command-line options and exit.
53
54 #### `-c`, `--code`
55
56 Format the code passed in as a string.
57
58 ```console
59 $ black --code "print ( 'hello, world' )"
60 print("hello, world")
61 ```
62
63 #### `-l`, `--line-length`
64
65 How many characters per line to allow. The default is 88.
66
67 See also [the style documentation](labels/line-length).
68
69 #### `-t`, `--target-version`
70
71 Python versions that should be supported by Black's output. You can run `black --help`
72 and look for the `--target-version` option to see the full list of supported versions.
73 You should include all versions that your code supports. If you support Python 3.11
74 through 3.13, you should write:
75
76 ```console
77 $ black -t py311 -t py312 -t py313
78 ```
79
80 In a [configuration file](#configuration-via-a-file), you can write:
81
82 ```toml
83 target-version = ["py311", "py312", "py313"]
84 ```
85
86 By default, Black will infer target versions from the project metadata in
87 `pyproject.toml`, specifically the `[project.requires-python]` field. If this does not
88 yield conclusive results, Black will use per-file auto-detection.
89
90 _Black_ uses this option to decide what grammar to use to parse your code. In addition,
91 it may use it to decide what style to use. For example, support for a trailing comma
92 after `*args` in a function call was added in Python 3.5, so _Black_ will add this comma
93 only if the target versions are all Python 3.5 or higher:
94
95 ```console
96 $ black --line-length=10 --target-version=py35 -c 'f(a, *args)'
97 f(
98 a,
99 *args,
100 )
101 $ black --line-length=10 --target-version=py34 -c 'f(a, *args)'
102 f(
103 a,
104 *args
105 )
106 $ black --line-length=10 --target-version=py34 --target-version=py35 -c 'f(a, *args)'
107 f(
108 a,
109 *args
110 )
111 ```
112
113 #### `--pyi`
114
115 Format all input files like typing stubs regardless of file extension. This is useful
116 when piping source on standard input.
117
118 #### `--ipynb`
119
120 Format all input files like Jupyter Notebooks regardless of file extension. This is
121 useful when piping source on standard input.
122
123 #### `--python-cell-magics`
124
125 When processing Jupyter Notebooks, add the given magic to the list of known python-
126 magics. Useful for formatting cells with custom python magics. See the
127 [Jupyter Notebooks guide](../guides/using_black_with_jupyter_notebooks.md) for more
128 details.
129
130 #### `-x, --skip-source-first-line`
131
132 Skip the first line of the source code.
133
134 #### `-S, --skip-string-normalization`
135
136 By default, _Black_ uses double quotes for all strings and normalizes string prefixes,
137 as described in [the style documentation](labels/strings). If this option is given,
138 strings are left unchanged instead.
139
140 #### `-C, --skip-magic-trailing-comma`
141
142 By default, _Black_ uses existing trailing commas as an indication that short lines
143 should be left separate, as described in
144 [the style documentation](labels/magic-trailing-comma). If this option is given, the
145 magic trailing comma is ignored.
146
147 #### `--preview`
148
149 Enable potentially disruptive style changes that we expect to add to Black's main
150 functionality in the next major release. Use this if you want a taste of what next
151 year's style will look like.
152
153 Read more about [our preview style](labels/preview-style).
154
155 There is no guarantee on the code style produced by this flag across releases.
156
157 #### `--unstable`
158
159 Enable all style changes in `--preview`, plus additional changes that we would like to
160 make eventually, but that have known issues that need to be fixed before they can move
161 back to the `--preview` style. Use this if you want to experiment with these changes and
162 help fix issues with them.
163
164 There is no guarantee on the code style produced by this flag across releases.
165
166 #### `--enable-unstable-feature`
167
168 Enable specific features from the `--unstable` style. See
169 [the preview style documentation](labels/unstable-features) for the list of supported
170 features. This flag can only be used when `--preview` is enabled. Users are encouraged
171 to use this flag if they use `--preview` style and a feature that affects their code is
172 moved from the `--preview` to the `--unstable` style, but they want to avoid the thrash
173 from undoing this change.
174
175 There are no guarantees on the behavior of these features, or even their existence,
176 across releases.
177
178 (labels/exit-code)=
179
180 #### `--check`
181
182 Don't write the files back, just return the status. _Black_ will exit with:
183
184 - code 0 if nothing would change;
185 - code 1 if some files would be reformatted; or
186 - code 123 if there was an internal error
187
188 If used in combination with `--quiet` then only the exit code will be returned, unless
189 there was an internal error.
190
191 ```console
192 $ black test.py --check
193 All done! ✨ 🍰 ✨
194 1 file would be left unchanged.
195 $ echo $?
196 0
197
198 $ black test.py --check
199 would reformat test.py
200 Oh no! πŸ’₯ πŸ’” πŸ’₯
201 1 file would be reformatted.
202 $ echo $?
203 1
204
205 $ black test.py --check
206 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
207 Oh no! πŸ’₯ πŸ’” πŸ’₯
208 1 file would fail to reformat.
209 $ echo $?
210 123
211 ```
212
213 #### `--diff`
214
215 Don't write the files back, just output a diff to indicate what changes _Black_ would've
216 made. They are printed to stdout so capturing them is simple.
217
218 If you'd like colored diffs, you can enable them with `--color`.
219
220 ```console
221 $ black test.py --diff
222 --- test.py 2021-03-08 22:23:40.848954+00:00
223 +++ test.py 2021-03-08 22:23:47.126319+00:00
224 @@ -1 +1 @@
225 -print ( 'hello, world' )
226 +print("hello, world")
227 would reformat test.py
228 All done! ✨ 🍰 ✨
229 1 file would be reformatted.
230 ```
231
232 #### `--no-cache`
233
234 Do not consult or update Black's per-user cache during this run. When `--no-cache` is
235 specified, Black will perform fresh analysis for all files and will neither read from
236 nor write to the cache. This is helpful for reproducing formatting results from a clean
237 run, debugging cache-related issues, or ensuring CI executes a fresh formatting analysis
238 every time.
239
240 #### `--color` / `--no-color`
241
242 Show (or do not show) colored diff. Only applies when `--diff` is given.
243
244 #### `--line-ranges`
245
246 When specified, _Black_ will try its best to only format these lines.
247
248 This option can be specified multiple times, and a union of the lines will be formatted.
249 Each range must be specified as two integers connected by a `-`: `<START>-<END>`. The
250 `<START>` and `<END>` integer indices are 1-based and inclusive on both ends.
251
252 _Black_ may still format lines outside of the ranges for multi-line statements.
253 Formatting more than one file or any Jupyter Notebooks with this option is not
254 supported. This option cannot be specified in the `pyproject.toml` config.
255
256 Example: `black --line-ranges=1-10 --line-ranges=21-30 test.py` will format lines from
257 `1` to `10` and `21` to `30`.
258
259 This option is mainly for editor integrations, such as "Format Selection".
260
261 ```{note}
262 Due to [#4052](https://github.com/psf/black/issues/4052), `--line-ranges` might format
263 extra lines outside of the ranges when there are unformatted lines with the exact
264 formatted content next to the requested lines. It also disables _Black_'s formatting
265 stability check in `--safe` mode.
266 ```
267
268 #### `--fast` / `--safe`
269
270 By default, _Black_ performs [an AST safety check](labels/ast-changes) after formatting
271 your code. The `--fast` flag turns off this check and the `--safe` flag explicitly
272 enables it.
273
274 #### `--required-version`
275
276 Require a specific version of _Black_ to be running. This is useful for ensuring that
277 all contributors to your project are using the same version, because different versions
278 of _Black_ may format code a little differently. This option can be set in a
279 configuration file for consistent results across environments.
280
281 ```console
282 $ black --version
283 black, 26.5.1 (compiled: yes)
284 $ black --required-version 26.5.1 -c "format = 'this'"
285 format = "this"
286 $ black --required-version 31.5b2 -c "still = 'beta?!'"
287 Oh no! πŸ’₯ πŸ’” πŸ’₯ The required version does not match the running version!
288 ```
289
290 You can also pass just the major version:
291
292 ```console
293 $ black --required-version 22 -c "format = 'this'"
294 format = "this"
295 $ black --required-version 31 -c "still = 'beta?!'"
296 Oh no! πŸ’₯ πŸ’” πŸ’₯ The required version does not match the running version!
297 ```
298
299 Because of our [stability policy](../the_black_code_style/index.md), this will guarantee
300 stable formatting, but still allow you to take advantage of improvements that do not
301 affect formatting.
302
303 #### `--exclude`
304
305 A regular expression that matches files and directories that should be excluded on
306 recursive searches. An empty value means no paths are excluded. Use forward slashes for
307 directories on all platforms (Windows, too). By default, Black also ignores all paths
308 listed in `.gitignore`. Changing this value will override all default exclusions.
309
310 Default Exclusions:
311 `['.direnv', '.eggs', '.git', '.hg', '.ipynb_checkpoints', '.mypy_cache', '.nox', '.pytest_cache', '.ruff_cache', '.tox', '.svn', '.venv', '.vscode', '__pypackages__', '_build', 'buck-out', 'build', 'dist', 'venv'] `
312
313 If the regular expression contains newlines, it is treated as a
314 [verbose regular expression](https://docs.python.org/3/library/re.html#re.VERBOSE). This
315 is typically useful when setting these options in a `pyproject.toml` configuration file;
316 see [Configuration format](#configuration-format) for more information.
317
318 #### `--extend-exclude`
319
320 Like `--exclude`, but adds additional files and directories on top of the default values
321 instead of overriding them.
322
323 #### `--force-exclude`
324
325 Like `--exclude`, but files and directories matching this regex will be excluded even
326 when they are passed explicitly as arguments. This is useful when invoking Black
327 programmatically on changed files, such as in a pre-commit hook or editor plugin.
328
329 #### `--stdin-filename`
330
331 The name of the file when passing it through stdin. Useful to make sure Black will
332 respect the `--force-exclude` option on some editors that rely on using stdin.
333
334 #### `--include`
335
336 A regular expression that matches files and directories that should be included on
337 recursive searches. An empty value means all files are included regardless of the name.
338 Use forward slashes for directories on all platforms (Windows, too). Overrides all
339 exclusions, including from `.gitignore` and command line options.
340
341 Default Inclusions: `['.pyi', '.ipynb']`
342
343 #### `-W`, `--workers`
344
345 When _Black_ formats multiple files, it may use a process pool to speed up formatting.
346 This option controls the number of parallel workers. This can also be specified via the
347 `BLACK_NUM_WORKERS` environment variable. Defaults to the number of CPUs in the system.
348
349 #### `-q`, `--quiet`
350
351 Stop emitting all non-critical output. Error messages will still be emitted (which can
352 silenced by `2>/dev/null`).
353
354 ```console
355 $ black src/ -q
356 error: cannot format src/black_primer/cli.py: Cannot parse: 5:6
357 mport asyncio
358 ^
359 ParseError: bad input
360 ```
361
362 #### `-v`, `--verbose`
363
364 Emit messages about files that were not changed or were ignored due to exclusion
365 patterns. If _Black_ is using a configuration file, a message detailing which one it is
366 using will be emitted.
367
368 ```console
369 $ black src/ -v
370 Using configuration from /tmp/pyproject.toml.
371 src/blib2to3 ignored: matches the --extend-exclude regular expression
372 src/_black_version.py wasn't modified on disk since last run.
373 src/black/__main__.py wasn't modified on disk since last run.
374 error: cannot format src/black_primer/cli.py: Cannot parse: 5:6
375 mport asyncio
376 ^
377 ParseError: bad input
378 reformatted src/black_primer/lib.py
379 reformatted src/blackd/__init__.py
380 reformatted src/black/__init__.py
381 Oh no! πŸ’₯ πŸ’” πŸ’₯
382 3 files reformatted, 2 files left unchanged, 1 file failed to reformat
383 ```
384
385 #### `--version`
386
387 You can check the version of _Black_ you have installed using the `--version` flag.
388
389 ```console
390 $ black --version
391 black, 26.5.1
392 ```
393
394 #### `--config`
395
396 Read configuration options from a configuration file. See
397 [below](#configuration-via-a-file) for more details on the configuration file.
398
399 ### Environment variable options
400
401 _Black_ supports the following configuration via environment variables.
402
403 #### `BLACK_CACHE_DIR`
404
405 The directory where _Black_ should store its cache.
406
407 #### `BLACK_NUM_WORKERS`
408
409 The number of parallel workers _Black_ should use. The command line option `-W` /
410 `--workers` takes precedence over this environment variable.
411
412 ### Code input alternatives
413
414 _Black_ supports formatting code via stdin, with the result being printed to stdout.
415 Just let _Black_ know with `-` as the path.
416
417 ```console
418 $ echo "print ( 'hello, world' )" | black -
419 print("hello, world")
420 reformatted -
421 All done! ✨ 🍰 ✨
422 1 file reformatted.
423 ```
424
425 **Tip:** if you need _Black_ to treat stdin input as a file passed directly via the CLI,
426 use `--stdin-filename`. Useful to make sure _Black_ will respect the `--force-exclude`
427 option on some editors that rely on using stdin.
428
429 You can also pass code as a string using the `--code` option.
430
431 ### Writeback and reporting
432
433 By default _Black_ reformats the files given and/or found in place. Sometimes you need
434 _Black_ to just tell you what it _would_ do without actually rewriting the Python files.
435
436 There's two variations to this mode that are independently enabled by their respective
437 flags:
438
439 - `--check` (exit with code 1 if any file would be reformatted)
440 - `--diff` (print a diff instead of reformatting files)
441
442 Both variations can be enabled at once.
443
444 ### Output verbosity
445
446 _Black_ in general tries to produce the right amount of output, balancing between
447 usefulness and conciseness. By default, _Black_ emits files modified and error messages,
448 plus a short summary.
449
450 ```console
451 $ black src/
452 error: cannot format src/black_primer/cli.py: Cannot parse: 5:6
453 mport asyncio
454 ^
455 ParseError: bad input
456 reformatted src/black_primer/lib.py
457 reformatted src/blackd/__init__.py
458 reformatted src/black/__init__.py
459 Oh no! πŸ’₯ πŸ’” πŸ’₯
460 3 files reformatted, 2 files left unchanged, 1 file failed to reformat.
461 ```
462
463 The `--quiet` and `--verbose` flags control output verbosity.
464
465 ## Configuration via a file
466
467 _Black_ is able to read project-specific default values for its command line options
468 from a `pyproject.toml` file. This is especially useful for specifying custom
469 `--include` and `--exclude`/`--force-exclude`/`--extend-exclude` patterns for your
470 project.
471
472 **Pro-tip**: If you're asking yourself "Do I need to configure anything?" the answer is
473 "No". _Black_ is all about sensible defaults. Applying those defaults will have your
474 code in compliance with many other _Black_ formatted projects.
475
476 ### What on Earth is a `pyproject.toml` file?
477
478 [PEP 518](https://peps.python.org/pep-0518/) defines `pyproject.toml` as a configuration
479 file to store build system requirements for Python projects. With the help of tools like
480 [Poetry](https://python-poetry.org/), [Flit](https://flit.readthedocs.io/en/latest/), or
481 [Hatch](https://hatch.pypa.io/latest/) it can fully replace the need for `setup.py` and
482 `setup.cfg` files.
483
484 ### Where _Black_ looks for the file
485
486 By default _Black_ looks for `pyproject.toml` containing a `[tool.black]` section
487 starting from the common base directory of all files and directories passed on the
488 command line. If it's not there, it looks in parent directories. It stops looking when
489 it finds the file, or a `.git` directory, or a `.hg` directory, or the root of the file
490 system, whichever comes first.
491
492 If you're formatting standard input, _Black_ will look for configuration starting from
493 the current working directory.
494
495 You can use a "global" configuration, stored in a specific location in your home
496 directory. This will be used as a fallback configuration, that is, it will be used if
497 and only if _Black_ doesn't find any configuration as mentioned above. Depending on your
498 operating system, this configuration file should be stored as:
499
500 - Windows: `~\.black`
501 - Unix-like (Linux, MacOS, etc.): `$XDG_CONFIG_HOME/black` (`~/.config/black` if the
502 `XDG_CONFIG_HOME` environment variable is not set)
503
504 Note that these are paths to the TOML file itself (meaning that they shouldn't be named
505 as `pyproject.toml`), not directories where you store the configuration (i.e.,
506 `black`/`.black` is the file to create and add your configuration options to, in the
507 `~/.config/` directory). Here, `~` refers to the path to your home directory. On
508 Windows, this will be something like `C:\Users\UserName` and stored in the environment
509 variable `%USERPROFILE%`.
510
511 You can also explicitly specify the path to a particular file that you want with
512 `--config`. In this situation _Black_ will not look for any other file.
513
514 If you're running with `--verbose`, you will see a message if a file was found and used.
515
516 Please note `blackd` will not use `pyproject.toml` configuration.
517
518 ### Configuration format
519
520 As the file extension suggests, `pyproject.toml` is a
521 [TOML](https://github.com/toml-lang/toml) file. It contains separate sections for
522 different tools. _Black_ is using the `[tool.black]` section. The option keys are the
523 same as long names of options on the command line.
524
525 Most command-line options can be configured in `[tool.black]` by using their long name
526 without the leading `--` (for example, `--line-length` becomes `line-length`). Options
527 that cannot be configured in `pyproject.toml` are called out explicitly in the option
528 reference above.
529
530 Note that you have to use single-quoted strings in TOML for regular expressions. It's
531 the equivalent of r-strings in Python. Multiline strings are treated as verbose regular
532 expressions by Black. Use `[ ]` to denote a significant space character.
533
534 <details>
535 <summary>Example <code>pyproject.toml</code></summary>
536
537 ```toml
538 [tool.black]
539 line-length = 88
540 target-version = ['py37']
541 include = '\.pyi?$'
542 # 'extend-exclude' excludes files or directories in addition to the defaults
543 extend-exclude = '''
544 # A regex preceded with ^/ will apply only to files and directories
545 # in the root of the project.
546 (
547 ^/foo.py # exclude a file named foo.py in the root of the project
548 | .*_pb2.py # exclude autogenerated Protocol Buffer files anywhere in the project
549 )
550 '''
551 ```
552
553 </details>
554
555 <details>
556 <summary>More complete <code>pyproject.toml</code> template</summary>
557
558 ```toml
559 [tool.black]
560 line-length = 88
561 target-version = ["py311"]
562 required-version = "26"
563 include = '\.pyi?$'
564
565 # Formatting behavior
566 skip-string-normalization = false
567 skip-magic-trailing-comma = false
568 preview = false
569 unstable = false
570
571 # File collection
572 extend-exclude = '''
573 (
574 ^/foo.py
575 | .*_pb2.py
576 )
577 '''
578 force-exclude = '''
579 (
580 ^/generated/
581 )
582 '''
583 ```
584
585 </details>
586
587 ### Lookup hierarchy
588
589 Command-line options have defaults that you can see in `--help`. A `pyproject.toml` can
590 override those defaults. Finally, options provided by the user on the command line
591 override both.
592
593 _Black_ will only ever use one `pyproject.toml` file during an entire run. It doesn't
594 look for multiple files, and doesn't compose configuration from different levels of the
595 file hierarchy.
596
597 ## Next steps
598
599 A good next step would be configuring auto-discovery so `black .` is all you need
600 instead of laborously listing every file or directory. You can get started by heading
601 over to [File collection and discovery](./file_collection_and_discovery.md).
602
603 Another good choice would be setting up an
604 [integration with your editor](../integrations/editors.md) of choice or with
605 [pre-commit for source version control](../integrations/source_version_control.md).