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 should include all
56 versions that your code supports. If you support Python 3.7 through 3.10, you should
60 $ black -t py37 -t py38 -t py39 -t py310
63 In a [configuration file](#configuration-via-a-file), you can write:
66 target-versions = ["py37", "py38", "py39", "py310"]
69 _Black_ uses this option to decide what grammar to use to parse your code. In addition,
70 it may use it to decide what style to use. For example, support for a trailing comma
71 after `*args` in a function call was added in Python 3.5, so _Black_ will add this comma
72 only if the target versions are all Python 3.5 or higher:
75 $ black --line-length=10 --target-version=py35 -c 'f(a, *args)'
80 $ black --line-length=10 --target-version=py34 -c 'f(a, *args)'
85 $ black --line-length=10 --target-version=py34 --target-version=py35 -c 'f(a, *args)'
94 Format all input files like typing stubs regardless of file extension. This is useful
95 when piping source on standard input.
99 Format all input files like Jupyter Notebooks regardless of file extension. This is
100 useful when piping source on standard input.
102 #### `--python-cell-magics`
104 When processing Jupyter Notebooks, add the given magic to the list of known python-
105 magics. Useful for formatting cells with custom python magics.
107 #### `-S, --skip-string-normalization`
109 By default, _Black_ uses double quotes for all strings and normalizes string prefixes,
110 as described in [the style documentation](labels/strings). If this option is given,
111 strings are left unchanged instead.
113 #### `-C, --skip-magic-trailing-comma`
115 By default, _Black_ uses existing trailing commas as an indication that short lines
116 should be left separate, as described in
117 [the style documentation](labels/magic-trailing-comma). If this option is given, the
118 magic trailing comma is ignored.
122 Enable potentially disruptive style changes that may be added to Black's main
123 functionality in the next major release. Read more about
124 [our preview style](labels/preview-style).
130 Passing `--check` will make _Black_ exit with:
132 - code 0 if nothing would change;
133 - code 1 if some files would be reformatted; or
134 - code 123 if there was an internal error
137 $ black test.py --check
139 1 file would be left unchanged.
143 $ black test.py --check
144 would reformat test.py
146 1 file would be reformatted.
150 $ black test.py --check
151 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 1 file would fail to reformat.
160 Passing `--diff` will make _Black_ print out diffs that indicate what changes _Black_
161 would've made. They are printed to stdout so capturing them is simple.
163 If you'd like colored diffs, you can enable them with `--color`.
166 $ black test.py --diff
167 --- test.py 2021-03-08 22:23:40.848954+00:00
168 +++ test.py 2021-03-08 22:23:47.126319+00:00
170 -print ( 'hello, world' )
171 +print("hello, world")
172 would reformat test.py
174 1 file would be reformatted.
177 #### `--color` / `--no-color`
179 Show (or do not show) colored diff. Only applies when `--diff` is given.
181 #### `--fast` / `--safe`
183 By default, _Black_ performs [an AST safety check](labels/ast-changes) after formatting
184 your code. The `--fast` flag turns off this check and the `--safe` flag explicitly
187 #### `--required-version`
189 Require a specific version of _Black_ to be running. This is useful for ensuring that
190 all contributors to your project are using the same version, because different versions
191 of _Black_ may format code a little differently. This option can be set in a
192 configuration file for consistent results across environments.
196 black, 23.3.0 (compiled: yes)
197 $ black --required-version 23.3.0 -c "format = 'this'"
199 $ black --required-version 31.5b2 -c "still = 'beta?!'"
200 Oh no! 💥 💔 💥 The required version does not match the running version!
203 You can also pass just the major version:
206 $ black --required-version 22 -c "format = 'this'"
208 $ black --required-version 31 -c "still = 'beta?!'"
209 Oh no! 💥 💔 💥 The required version does not match the running version!
212 Because of our [stability policy](../the_black_code_style/index.md), this will guarantee
213 stable formatting, but still allow you to take advantage of improvements that do not
218 A regular expression that matches files and directories that should be included on
219 recursive searches. An empty value means all files are included regardless of the name.
220 Use forward slashes for directories on all platforms (Windows, too). Exclusions are
221 calculated first, inclusions later.
225 A regular expression that matches files and directories that should be excluded on
226 recursive searches. An empty value means no paths are excluded. Use forward slashes for
227 directories on all platforms (Windows, too). Exclusions are calculated first, inclusions
230 #### `--extend-exclude`
232 Like `--exclude`, but adds additional files and directories on top of the excluded ones.
233 Useful if you simply want to add to the default.
235 #### `--force-exclude`
237 Like `--exclude`, but files and directories matching this regex will be excluded even
238 when they are passed explicitly as arguments. This is useful when invoking _Black_
239 programmatically on changed files, such as in a pre-commit hook or editor plugin.
241 #### `--stdin-filename`
243 The name of the file when passing it through stdin. Useful to make sure Black will
244 respect the `--force-exclude` option on some editors that rely on using stdin.
246 #### `-W`, `--workers`
248 When _Black_ formats multiple files, it may use a process pool to speed up formatting.
249 This option controls the number of parallel workers. This can also be specified via the
250 `BLACK_NUM_WORKERS` environment variable.
254 Passing `-q` / `--quiet` will cause _Black_ to stop emitting all non-critical output.
255 Error messages will still be emitted (which can silenced by `2>/dev/null`).
259 error: cannot format src/black_primer/cli.py: Cannot parse: 5:6: mport asyncio
262 #### `-v`, `--verbose`
264 Passing `-v` / `--verbose` will cause _Black_ to also emit messages about files that
265 were not changed or were ignored due to exclusion patterns. If _Black_ is using a
266 configuration file, a blue message detailing which one it is using will be emitted.
270 Using configuration from /tmp/pyproject.toml.
271 src/blib2to3 ignored: matches the --extend-exclude regular expression
272 src/_black_version.py wasn't modified on disk since last run.
273 src/black/__main__.py wasn't modified on disk since last run.
274 error: cannot format src/black_primer/cli.py: Cannot parse: 5:6: mport asyncio
275 reformatted src/black_primer/lib.py
276 reformatted src/blackd/__init__.py
277 reformatted src/black/__init__.py
279 3 files reformatted, 2 files left unchanged, 1 file failed to reformat
284 You can check the version of _Black_ you have installed using the `--version` flag.
293 Read configuration options from a configuration file. See
294 [below](#configuration-via-a-file) for more details on the configuration file.
298 Show available command-line options and exit.
300 ### Environment variable options
302 _Black_ supports the following configuration via environment variables.
304 #### `BLACK_CACHE_DIR`
306 The directory where _Black_ should store its cache.
308 #### `BLACK_NUM_WORKERS`
310 The number of parallel workers _Black_ should use. The command line option `-W` /
311 `--workers` takes precedence over this environment variable.
313 ### Code input alternatives
315 _Black_ supports formatting code via stdin, with the result being printed to stdout.
316 Just let _Black_ know with `-` as the path.
319 $ echo "print ( 'hello, world' )" | black -
320 print("hello, world")
326 **Tip:** if you need _Black_ to treat stdin input as a file passed directly via the CLI,
327 use `--stdin-filename`. Useful to make sure _Black_ will respect the `--force-exclude`
328 option on some editors that rely on using stdin.
330 You can also pass code as a string using the `-c` / `--code` option.
332 ### Writeback and reporting
334 By default _Black_ reformats the files given and/or found in place. Sometimes you need
335 _Black_ to just tell you what it _would_ do without actually rewriting the Python files.
337 There's two variations to this mode that are independently enabled by their respective
340 - `--check` (exit with code 1 if any file would be reformatted)
341 - `--diff` (print a diff instead of reformatting files)
343 Both variations can be enabled at once.
347 _Black_ in general tries to produce the right amount of output, balancing between
348 usefulness and conciseness. By default, _Black_ emits files modified and error messages,
349 plus a short summary.
353 error: cannot format src/black_primer/cli.py: Cannot parse: 5:6: mport asyncio
354 reformatted src/black_primer/lib.py
355 reformatted src/blackd/__init__.py
356 reformatted src/black/__init__.py
358 3 files reformatted, 2 files left unchanged, 1 file failed to reformat.
361 The `--quiet` and `--verbose` flags control output verbosity.
363 ## Configuration via a file
365 _Black_ is able to read project-specific default values for its command line options
366 from a `pyproject.toml` file. This is especially useful for specifying custom
367 `--include` and `--exclude`/`--force-exclude`/`--extend-exclude` patterns for your
370 **Pro-tip**: If you're asking yourself "Do I need to configure anything?" the answer is
371 "No". _Black_ is all about sensible defaults. Applying those defaults will have your
372 code in compliance with many other _Black_ formatted projects.
374 ### What on Earth is a `pyproject.toml` file?
376 [PEP 518](https://www.python.org/dev/peps/pep-0518/) defines `pyproject.toml` as a
377 configuration file to store build system requirements for Python projects. With the help
378 of tools like [Poetry](https://python-poetry.org/),
379 [Flit](https://flit.readthedocs.io/en/latest/), or
380 [Hatch](https://hatch.pypa.io/latest/) it can fully replace the need for `setup.py` and
383 ### Where _Black_ looks for the file
385 By default _Black_ looks for `pyproject.toml` starting from the common base directory of
386 all files and directories passed on the command line. If it's not there, it looks in
387 parent directories. It stops looking when it finds the file, or a `.git` directory, or a
388 `.hg` directory, or the root of the file system, whichever comes first.
390 If you're formatting standard input, _Black_ will look for configuration starting from
391 the current working directory.
393 You can use a "global" configuration, stored in a specific location in your home
394 directory. This will be used as a fallback configuration, that is, it will be used if
395 and only if _Black_ doesn't find any configuration as mentioned above. Depending on your
396 operating system, this configuration file should be stored as:
398 - Windows: `~\.black`
399 - Unix-like (Linux, MacOS, etc.): `$XDG_CONFIG_HOME/black` (`~/.config/black` if the
400 `XDG_CONFIG_HOME` environment variable is not set)
402 Note that these are paths to the TOML file itself (meaning that they shouldn't be named
403 as `pyproject.toml`), not directories where you store the configuration. Here, `~`
404 refers to the path to your home directory. On Windows, this will be something like
405 `C:\\Users\UserName`.
407 You can also explicitly specify the path to a particular file that you want with
408 `--config`. In this situation _Black_ will not look for any other file.
410 If you're running with `--verbose`, you will see a blue message if a file was found and
413 Please note `blackd` will not use `pyproject.toml` configuration.
415 ### Configuration format
417 As the file extension suggests, `pyproject.toml` is a
418 [TOML](https://github.com/toml-lang/toml) file. It contains separate sections for
419 different tools. _Black_ is using the `[tool.black]` section. The option keys are the
420 same as long names of options on the command line.
422 Note that you have to use single-quoted strings in TOML for regular expressions. It's
423 the equivalent of r-strings in Python. Multiline strings are treated as verbose regular
424 expressions by Black. Use `[ ]` to denote a significant space character.
427 <summary>Example <code>pyproject.toml</code></summary>
432 target-version = ['py37']
434 # 'extend-exclude' excludes files or directories in addition to the defaults
436 # A regex preceded with ^/ will apply only to files and directories
437 # in the root of the project.
439 ^/foo.py # exclude a file named foo.py in the root of the project
440 | .*_pb2.py # exclude autogenerated Protocol Buffer files anywhere in the project
449 Command-line options have defaults that you can see in `--help`. A `pyproject.toml` can
450 override those defaults. Finally, options provided by the user on the command line
453 _Black_ will only ever use one `pyproject.toml` file during an entire run. It doesn't
454 look for multiple files, and doesn't compose configuration from different levels of the
459 A good next step would be configuring auto-discovery so `black .` is all you need
460 instead of laborously listing every file or directory. You can get started by heading
461 over to [File collection and discovery](./file_collection_and_discovery.md).
463 Another good choice would be setting up an
464 [integration with your editor](../integrations/editors.md) of choice or with
465 [pre-commit for source version control](../integrations/source_version_control.md).