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.
3 Foundational knowledge on using and configuring Black.
5 _Black_ is a well-behaved Unix-style command-line tool:
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
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.
15 To get started right away with sensible defaults:
18 black {source_file_or_directory}
21 You can run _Black_ as a package if running it as a script doesn't work:
24 python -m black {source_file_or_directory}
27 ### Command line options
29 The CLI options of _Black_ can be displayed by running `black --help`. All options are
30 also covered in more detail below.
32 While _Black_ has quite a few knobs these days, it is still opinionated so style options
33 are deliberately limited and rarely added.
35 Note that all command-line options listed above can also be configured using a
36 `pyproject.toml` file (more on that below).
40 Format the code passed in as a string.
43 $ black --code "print ( 'hello, world' )"
47 #### `-l`, `--line-length`
49 How many characters per line to allow. The default is 88.
51 See also [the style documentation](labels/line-length).
53 #### `-t`, `--target-version`
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:
61 $ black -t py38 -t py39 -t py310 -t py311
64 In a [configuration file](#configuration-via-a-file), you can write:
67 target-version = ["py38", "py39", "py310", "py311"]
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:
76 $ black --line-length=10 --target-version=py35 -c 'f(a, *args)'
81 $ black --line-length=10 --target-version=py34 -c 'f(a, *args)'
86 $ black --line-length=10 --target-version=py34 --target-version=py35 -c 'f(a, *args)'
95 Format all input files like typing stubs regardless of file extension. This is useful
96 when piping source on standard input.
100 Format all input files like Jupyter Notebooks regardless of file extension. This is
101 useful when piping source on standard input.
103 #### `--python-cell-magics`
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.
108 #### `-S, --skip-string-normalization`
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.
114 #### `-C, --skip-magic-trailing-comma`
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.
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).
131 Passing `--check` will make _Black_ exit with:
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
138 $ black test.py --check
139 All done! β¨ π° β¨
140 1 file would be left unchanged.
144 $ black test.py --check
145 would reformat test.py
146 Oh no! π₯ π π₯
147 1 file would be reformatted.
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.
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.
164 If you'd like colored diffs, you can enable them with `--color`.
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
171 -print ( 'hello, world' )
172 +print("hello, world")
173 would reformat test.py
174 All done! β¨ π° β¨
175 1 file would be reformatted.
178 #### `--color` / `--no-color`
180 Show (or do not show) colored diff. Only applies when `--diff` is given.
182 #### `--fast` / `--safe`
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
188 #### `--required-version`
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.
197 black, 23.9.1 (compiled: yes)
198 $ black --required-version 23.9.1 -c "format = 'this'"
200 $ black --required-version 31.5b2 -c "still = 'beta?!'"
201 Oh no! π₯ π π₯ The required version does not match the running version!
204 You can also pass just the major version:
207 $ black --required-version 22 -c "format = 'this'"
209 $ black --required-version 31 -c "still = 'beta?!'"
210 Oh no! π₯ π π₯ The required version does not match the running version!
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
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.
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
231 #### `--extend-exclude`
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.
236 #### `--force-exclude`
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.
242 #### `--stdin-filename`
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.
247 #### `-W`, `--workers`
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.
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`).
260 error: cannot format src/black_primer/cli.py: Cannot parse: 5:6: mport asyncio
263 #### `-v`, `--verbose`
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.
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
285 You can check the version of _Black_ you have installed using the `--version` flag.
294 Read configuration options from a configuration file. See
295 [below](#configuration-via-a-file) for more details on the configuration file.
299 Show available command-line options and exit.
301 ### Environment variable options
303 _Black_ supports the following configuration via environment variables.
305 #### `BLACK_CACHE_DIR`
307 The directory where _Black_ should store its cache.
309 #### `BLACK_NUM_WORKERS`
311 The number of parallel workers _Black_ should use. The command line option `-W` /
312 `--workers` takes precedence over this environment variable.
314 ### Code input alternatives
316 _Black_ supports formatting code via stdin, with the result being printed to stdout.
317 Just let _Black_ know with `-` as the path.
320 $ echo "print ( 'hello, world' )" | black -
321 print("hello, world")
323 All done! β¨ π° β¨
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.
331 You can also pass code as a string using the `-c` / `--code` option.
333 ### Writeback and reporting
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.
338 There's two variations to this mode that are independently enabled by their respective
341 - `--check` (exit with code 1 if any file would be reformatted)
342 - `--diff` (print a diff instead of reformatting files)
344 Both variations can be enabled at once.
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.
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.
362 The `--quiet` and `--verbose` flags control output verbosity.
364 ## Configuration via a file
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
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.
375 ### What on Earth is a `pyproject.toml` file?
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
384 ### Where _Black_ looks for the file
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.
391 If you're formatting standard input, _Black_ will look for configuration starting from
392 the current working directory.
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:
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)
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`.
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.
411 If you're running with `--verbose`, you will see a blue message if a file was found and
414 Please note `blackd` will not use `pyproject.toml` configuration.
416 ### Configuration format
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.
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.
428 <summary>Example <code>pyproject.toml</code></summary>
433 target-version = ['py37']
435 # 'extend-exclude' excludes files or directories in addition to the defaults
437 # A regex preceded with ^/ will apply only to files and directories
438 # in the root of the project.
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
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
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
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).
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).