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.
1 ![Black Logo](https://raw.githubusercontent.com/psf/black/master/docs/_static/logo2-readme.png)
3 <h2 align="center">The Uncompromising Code Formatter</h2>
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://github.com/psf/black/actions"><img alt="Actions Status" src="https://github.com/psf/black/workflows/Primer/badge.svg"></a>
9 <a href="https://black.readthedocs.io/en/stable/?badge=stable"><img alt="Documentation Status" src="https://readthedocs.org/projects/black/badge/?version=stable"></a>
10 <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>
11 <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>
12 <a href="https://pypi.org/project/black/"><img alt="PyPI" src="https://img.shields.io/pypi/v/black"></a>
13 <a href="https://pepy.tech/project/black"><img alt="Downloads" src="https://pepy.tech/badge/black"></a>
14 <a href="https://github.com/psf/black"><img alt="Code style: black" src="https://img.shields.io/badge/code%20style-black-000000.svg"></a>
17 > “Any color you like.”
19 _Black_ is the uncompromising Python code formatter. By using it, you agree to cede
20 control over minutiae of hand-formatting. In return, _Black_ gives you speed,
21 determinism, and freedom from `pycodestyle` nagging about formatting. You will save time
22 and mental energy for more important matters.
24 Blackened code looks the same regardless of the project you're reading. Formatting
25 becomes transparent after a while and you can focus on the content instead.
27 _Black_ makes code review faster by producing the smallest diffs possible.
29 Try it out now using the [Black Playground](https://black.now.sh). Watch the
30 [PyCon 2019 talk](https://youtu.be/esZLCuWs_2Y) to learn more.
34 _Contents:_ **[Installation and usage](#installation-and-usage)** |
35 **[Code style](#the-black-code-style)** | **[Pragmatism](#pragmatism)** |
36 **[pyproject.toml](#pyprojecttoml)** | **[Editor integration](#editor-integration)** |
37 **[blackd](#blackd)** | **[black-primer](#black-primer)** |
38 **[Version control integration](#version-control-integration)** |
39 **[Ignoring unmodified files](#ignoring-unmodified-files)** | **[Used by](#used-by)** |
40 **[Testimonials](#testimonials)** | **[Show your style](#show-your-style)** |
41 **[Contributing](#contributing-to-black)** | **[Change log](#change-log)** |
42 **[Authors](#authors)**
46 ## Installation and usage
50 _Black_ can be installed by running `pip install black`. It requires Python 3.6.0+ to
51 run but you can reformat Python 2 code with it, too.
55 To get started right away with sensible defaults:
58 black {source_file_or_directory}
61 You can run _Black_ as a package if running it as a script doesn't work:
64 python -m black {source_file_or_directory}
67 ### Command line options
69 _Black_ doesn't provide many options. You can list them by running `black --help`:
72 Usage: black [OPTIONS] [SRC]...
74 The uncompromising code formatter.
77 -c, --code TEXT Format the code passed in as a string.
78 -l, --line-length INTEGER How many characters per line to allow.
81 -t, --target-version [py27|py33|py34|py35|py36|py37|py38]
82 Python versions that should be supported by
83 Black's output. [default: per-file auto-
86 --pyi Format all input files like typing stubs
87 regardless of file extension (useful when
88 piping source on standard input).
90 -S, --skip-string-normalization
91 Don't normalize string quotes or prefixes.
92 --check Don't write the files back, just return the
93 status. Return code 0 means nothing would
94 change. Return code 1 means some files
95 would be reformatted. Return code 123 means
96 there was an internal error.
98 --diff Don't write the files back, just output a
99 diff for each file on stdout.
101 --color / --no-color Show colored diff. Only applies when
104 --fast / --safe If --fast given, skip temporary sanity
105 checks. [default: --safe]
107 --include TEXT A regular expression that matches files and
108 directories that should be included on
109 recursive searches. An empty value means
110 all files are included regardless of the
111 name. Use forward slashes for directories
112 on all platforms (Windows, too). Exclusions
113 are calculated first, inclusions later.
116 --exclude TEXT A regular expression that matches files and
117 directories that should be excluded on
118 recursive searches. An empty value means no
119 paths are excluded. Use forward slashes for
120 directories on all platforms (Windows, too).
121 Exclusions are calculated first, inclusions
122 later. [default: /(\.eggs|\.git|\.hg|\.mypy
123 _cache|\.nox|\.tox|\.venv|\.svn|_build|buck-
126 --force-exclude TEXT Like --exclude, but files and directories
127 matching this regex will be excluded even
128 when they are passed explicitly as arguments
130 -q, --quiet Don't emit non-error messages to stderr.
131 Errors are still emitted; silence those with
134 -v, --verbose Also emit messages to stderr about files
135 that were not changed or were ignored due to
138 --version Show the version and exit.
139 --config FILE Read configuration from PATH.
140 -h, --help Show this message and exit.
143 _Black_ is a well-behaved Unix-style command-line tool:
145 - it does nothing if no sources are passed to it;
146 - it will read from standard input and write to standard output if `-` is used as the
148 - it only outputs messages to users on standard error;
149 - exits with code 0 unless an internal error occurred (or `--check` was used).
151 ### Using _Black_ with other tools
153 While _Black_ enforces formatting that conforms to PEP 8, other tools may raise warnings
154 about _Black_'s changes or will overwrite _Black_'s changes. A good example of this is
155 [isort](https://pypi.org/p/isort). Since _Black_ is barely configurable, these tools
156 should be configured to neither warn about nor overwrite _Black_'s changes.
158 Actual details on _Black_ compatible configurations for various tools can be found in
159 [compatible_configs](https://github.com/psf/black/blob/master/docs/compatible_configs.md).
161 ### Migrating your code style without ruining git blame
163 A long-standing argument against moving to automated code formatters like _Black_ is
164 that the migration will clutter up the output of `git blame`. This was a valid argument,
165 but since Git version 2.23, Git natively supports
166 [ignoring revisions in blame](https://git-scm.com/docs/git-blame#Documentation/git-blame.txt---ignore-revltrevgt)
167 with the `--ignore-rev` option. You can also pass a file listing the revisions to ignore
168 using the `--ignore-revs-file` option. The changes made by the revision will be ignored
169 when assigning blame. Lines modified by an ignored revision will be blamed on the
170 previous revision that modified those lines.
172 So when migrating your project's code style to _Black_, reformat everything and commit
173 the changes (preferably in one massive commit). Then put the full 40 characters commit
174 identifier(s) into a file.
177 # Migrate code style to Black
178 5b4ab991dede475d393e9d69ec388fd6bd949699
181 Afterwards, you can pass that file to `git blame` and see clean and meaningful blame
185 $ git blame important.py --ignore-revs-file .git-blame-ignore-revs
186 7a1ae265 (John Smith 2019-04-15 15:55:13 -0400 1) def very_important_function(text, file):
187 abdfd8b0 (Alice Doe 2019-09-23 11:39:32 -0400 2) text = text.lstrip()
188 7a1ae265 (John Smith 2019-04-15 15:55:13 -0400 3) with open(file, "r+") as f:
189 7a1ae265 (John Smith 2019-04-15 15:55:13 -0400 4) f.write(formatted)
192 You can even configure `git` to automatically ignore revisions listed in a file on every
196 $ git config blame.ignoreRevsFile .git-blame-ignore-revs
199 **The one caveat is that GitHub and GitLab do not yet support ignoring revisions using
200 their native UI of blame.** So blame information will be cluttered with a reformatting
201 commit on those platforms. (If you'd like this feature, there's an open issue for
202 [GitLab](https://gitlab.com/gitlab-org/gitlab/-/issues/31423) and please let GitHub
205 ### NOTE: This is a beta product
207 _Black_ is already [successfully used](#used-by) by many projects, small and big. It
208 also sports a decent test suite. However, it is still very new. Things will probably be
209 wonky for a while. This is made explicit by the "Beta" trove classifier, as well as by
210 the "b" in the version number. What this means for you is that **until the formatter
211 becomes stable, you should expect some formatting to change in the future**. That being
212 said, no drastic stylistic changes are planned, mostly responses to bug reports.
214 Also, as a temporary safety measure, _Black_ will check that the reformatted code still
215 produces a valid AST that is equivalent to the original. This slows it down. If you're
216 feeling confident, use `--fast`.
218 ## The _Black_ code style
220 _Black_ is a PEP 8 compliant opinionated formatter. _Black_ reformats entire files in
221 place. It is not configurable. It doesn't take previous formatting into account. Your
222 main option of configuring _Black_ is that it doesn't reformat blocks that start with
223 `# fmt: off` and end with `# fmt: on`. `# fmt: on/off` have to be on the same level of
224 indentation. To learn more about _Black_'s opinions, to go
225 [the_black_code_style](https://github.com/psf/black/blob/master/docs/the_black_code_style.md).
227 Please refer to this document before submitting an issue. What seems like a bug might be
232 Early versions of _Black_ used to be absolutist in some respects. They took after its
233 initial author. This was fine at the time as it made the implementation simpler and
234 there were not many users anyway. Not many edge cases were reported. As a mature tool,
235 _Black_ does make some exceptions to rules it otherwise holds. This
236 [section](https://github.com/psf/black/blob/master/docs/the_black_code_style.md#pragmatism)
237 of `the_black_code_style` describes what those exceptions are and why this is the case.
239 Please refer to this document before submitting an issue just like with the document
240 above. What seems like a bug might be intended behaviour.
244 _Black_ is able to read project-specific default values for its command line options
245 from a `pyproject.toml` file. This is especially useful for specifying custom
246 `--include` and `--exclude` patterns for your project.
248 **Pro-tip**: If you're asking yourself "Do I need to configure anything?" the answer is
249 "No". _Black_ is all about sensible defaults.
251 ### What on Earth is a `pyproject.toml` file?
253 [PEP 518](https://www.python.org/dev/peps/pep-0518/) defines `pyproject.toml` as a
254 configuration file to store build system requirements for Python projects. With the help
255 of tools like [Poetry](https://python-poetry.org/) or
256 [Flit](https://flit.readthedocs.io/en/latest/) it can fully replace the need for
257 `setup.py` and `setup.cfg` files.
259 ### Where _Black_ looks for the file
261 By default _Black_ looks for `pyproject.toml` starting from the common base directory of
262 all files and directories passed on the command line. If it's not there, it looks in
263 parent directories. It stops looking when it finds the file, or a `.git` directory, or a
264 `.hg` directory, or the root of the file system, whichever comes first.
266 If you're formatting standard input, _Black_ will look for configuration starting from
267 the current working directory.
269 You can also explicitly specify the path to a particular file that you want with
270 `--config`. In this situation _Black_ will not look for any other file.
272 If you're running with `--verbose`, you will see a blue message if a file was found and
275 Please note `blackd` will not use `pyproject.toml` configuration.
277 ### Configuration format
279 As the file extension suggests, `pyproject.toml` is a
280 [TOML](https://github.com/toml-lang/toml) file. It contains separate sections for
281 different tools. _Black_ is using the `[tool.black]` section. The option keys are the
282 same as long names of options on the command line.
284 Note that you have to use single-quoted strings in TOML for regular expressions. It's
285 the equivalent of r-strings in Python. Multiline strings are treated as verbose regular
286 expressions by Black. Use `[ ]` to denote a significant space character.
289 <summary>Example `pyproject.toml`</summary>
294 target-version = ['py37']
300 \.eggs # exclude a few common directories in the
301 | \.git # root of the project
311 | foo.py # also separately exclude a file named foo.py in
312 # the root of the project
321 Command-line options have defaults that you can see in `--help`. A `pyproject.toml` can
322 override those defaults. Finally, options provided by the user on the command line
325 _Black_ will only ever use one `pyproject.toml` file during an entire run. It doesn't
326 look for multiple files, and doesn't compose configuration from different levels of the
329 ## Editor integration
331 _Black_ can be integrated into many editors with plugins. They let you run _Black_ on
332 your code with the ease of doing it in your editor. To get started using _Black_ in your
333 editor of choice, please see
334 [editor_integration](https://github.com/psf/black/blob/master/docs/editor_integration.md).
336 Patches are welcome for editors without an editor integration or plugin! More
337 information can be found in
338 [editor_integration](https://github.com/psf/black/blob/master/docs/editor_integration.md#other-editors).
342 `blackd` is a small HTTP server that exposes Black's functionality over a simple
343 protocol. The main benefit of using it is to avoid paying the cost of starting up a new
344 Black process every time you want to blacken a file. Please refer to
345 [blackd](https://github.com/psf/black/blob/master/docs/blackd.md) to get the ball
350 `black-primer` is a tool built for CI (and huumans) to have _Black_ `--check` a number
351 of (configured in `primer.json`) Git accessible projects in parallel.
352 [black_primer](https://github.com/psf/black/blob/master/docs/black_primer.md) has more
353 information regarding its usage and configuration.
355 (A PR adding Mercurial support will be accepted.)
357 ## Version control integration
359 Use [pre-commit](https://pre-commit.com/). Once you
360 [have it installed](https://pre-commit.com/#install), add this to the
361 `.pre-commit-config.yaml` in your repository:
365 - repo: https://github.com/psf/black
369 language_version: python3.6
372 Then run `pre-commit install` and you're ready to go.
374 Avoid using `args` in the hook. Instead, store necessary configuration in
375 `pyproject.toml` so that editors and command-line usage of Black all behave consistently
376 for your project. See _Black_'s own
377 [pyproject.toml](https://github.com/psf/black/blob/master/pyproject.toml) for an
380 If you're already using Python 3.7, switch the `language_version` accordingly. Finally,
381 `stable` is a branch that tracks the latest release on PyPI. If you'd rather run on
382 master, this is also an option.
384 ## Ignoring unmodified files
386 _Black_ remembers files it has already formatted, unless the `--diff` flag is used or
387 code is passed via standard input. This information is stored per-user. The exact
388 location of the file depends on the _Black_ version and the system on which _Black_ is
389 run. The file is non-portable. The standard location on common operating systems is:
392 `C:\\Users\<username>\AppData\Local\black\black\Cache\<version>\cache.<line-length>.<file-mode>.pickle`
394 `/Users/<username>/Library/Caches/black/<version>/cache.<line-length>.<file-mode>.pickle`
396 `/home/<username>/.cache/black/<version>/cache.<line-length>.<file-mode>.pickle`
398 `file-mode` is an int flag that determines whether the file was formatted as 3.6+ only,
399 as .pyi, and whether string normalization was omitted.
401 To override the location of these files on macOS or Linux, set the environment variable
402 `XDG_CACHE_HOME` to your preferred location. For example, if you want to put the cache
403 in the directory you're running _Black_ from, set `XDG_CACHE_HOME=.cache`. _Black_ will
404 then write the above files to `.cache/black/<version>/`.
408 The following notable open-source projects trust _Black_ with enforcing a consistent
409 code style: pytest, tox, Pyramid, Django Channels, Hypothesis, attrs, SQLAlchemy,
410 Poetry, PyPA applications (Warehouse, Bandersnatch, Pipenv, virtualenv), pandas, Pillow,
411 every Datadog Agent Integration, Home Assistant.
413 The following organizations use _Black_: Facebook, Dropbox.
415 Are we missing anyone? Let us know.
420 [writer](https://smile.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=dusty+phillips):
422 > _Black_ is opinionated so you don't have to be.
424 **Hynek Schlawack**, [creator of `attrs`](https://www.attrs.org/), core developer of
427 > An auto-formatter that doesn't suck is all I want for Xmas!
429 **Carl Meyer**, [Django](https://www.djangoproject.com/) core developer:
431 > At least the name is good.
433 **Kenneth Reitz**, creator of [`requests`](http://python-requests.org/) and
434 [`pipenv`](https://readthedocs.org/projects/pipenv/):
436 > This vastly improves the formatting of our code. Thanks a ton!
440 Use the badge in your project's README.md:
443 [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
446 Using the badge in README.rst:
449 .. image:: https://img.shields.io/badge/code%20style-black-000000.svg
450 :target: https://github.com/psf/black
454 [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
460 ## Contributing to _Black_
462 In terms of inspiration, _Black_ is about as configurable as _gofmt_. This is
465 Bug reports and fixes are always welcome! However, before you suggest a new feature or
466 configuration knob, ask yourself why you want it. If it enables better integration with
467 some workflow, fixes an inconsistency, speeds things up, and so on - go for it! On the
468 other hand, if your answer is "because I don't like a particular formatting" then you're
469 not ready to embrace _Black_ yet. Such changes are unlikely to get accepted. You can
470 still try but prepare to be disappointed.
472 More details can be found in
473 [CONTRIBUTING](https://github.com/psf/black/blob/master/CONTRIBUTING.md).
477 The log's become rather long. It moved to its own file.
479 See [CHANGES](https://github.com/psf/black/blob/master/CHANGES.md).
483 Glued together by [Łukasz Langa](mailto:lukasz@langa.pl).
485 Maintained with [Carol Willing](mailto:carolcode@willingconsulting.com),
486 [Carl Meyer](mailto:carl@oddbird.net),
487 [Jelle Zijlstra](mailto:jelle.zijlstra@gmail.com),
488 [Mika Naylor](mailto:mail@autophagy.io),
489 [Zsolt Dollenstein](mailto:zsol.zsol@gmail.com), and
490 [Cooper Lees](mailto:me@cooperlees.com).
492 Multiple contributions by:
494 - [Abdur-Rahmaan Janhangeer](mailto:arj.python@gmail.com)
495 - [Adam Johnson](mailto:me@adamj.eu)
496 - [Alexander Huynh](mailto:github@grande.coffee)
497 - [Andrew Thorp](mailto:andrew.thorp.dev@gmail.com)
498 - [Andrey](mailto:dyuuus@yandex.ru)
499 - [Andy Freeland](mailto:andy@andyfreeland.net)
500 - [Anthony Sottile](mailto:asottile@umich.edu)
501 - [Arjaan Buijk](mailto:arjaan.buijk@gmail.com)
502 - [Artem Malyshev](mailto:proofit404@gmail.com)
503 - [Asger Hautop Drewsen](mailto:asgerdrewsen@gmail.com)
504 - [Augie Fackler](mailto:raf@durin42.com)
505 - [Aviskar KC](mailto:aviskarkc10@gmail.com)
506 - [Benjamin Woodruff](mailto:github@benjam.info)
507 - [Brandt Bucher](mailto:brandtbucher@gmail.com)
509 - [Christian Heimes](mailto:christian@python.org)
510 - [Chuck Wooters](mailto:chuck.wooters@microsoft.com)
511 - [Cooper Ry Lees](mailto:me@cooperlees.com)
512 - [Daniel Hahler](mailto:github@thequod.de)
513 - [Daniel M. Capella](mailto:polycitizen@gmail.com)
516 - [Eli Treuherz](mailto:eli@treuherz.com)
517 - [Florent Thiery](mailto:fthiery@gmail.com)
520 - [Ivan Katanić](mailto:ivan.katanic@gmail.com)
521 - [Jason Fried](mailto:me@jasonfried.info)
522 - [jgirardet](mailto:ijkl@netc.fr)
523 - [Joe Antonakakis](mailto:jma353@cornell.edu)
524 - [Jon Dufresne](mailto:jon.dufresne@gmail.com)
525 - [Jonas Obrist](mailto:ojiidotch@gmail.com)
526 - [Josh Bode](mailto:joshbode@fastmail.com)
527 - [Juan Luis Cano Rodríguez](mailto:hello@juanlu.space)
528 - [Katie McLaughlin](mailto:katie@glasnt.com)
530 - [Linus Groh](mailto:mail@linusgroh.de)
531 - [Luka Sterbic](mailto:luka.sterbic@gmail.com)
533 - [Matt VanEseltine](mailto:vaneseltine@gmail.com)
534 - [Michael Flaxman](mailto:michael.flaxman@gmail.com)
535 - [Michael J. Sullivan](mailto:sully@msully.net)
536 - [Michael McClimon](mailto:michael@mcclimon.org)
537 - [Miguel Gaiowski](mailto:miggaiowski@gmail.com)
538 - [Mike](mailto:roshi@fedoraproject.org)
539 - [Min ho Kim](mailto:minho42@gmail.com)
540 - [Miroslav Shubernetskiy](mailto:miroslav@miki725.com)
541 - [Neraste](mailto:neraste.herr10@gmail.com)
542 - [Ofek Lev](mailto:ofekmeister@gmail.com)
543 - [Osaetin Daniel](mailto:osaetindaniel@gmail.com)
544 - [Pablo Galindo](mailto:Pablogsal@gmail.com)
545 - [Peter Bengtsson](mailto:mail@peterbe.com)
548 - [Rishikesh Jha](mailto:rishijha424@gmail.com)
549 - [Stavros Korokithakis](mailto:hi@stavros.io)
550 - [Stephen Rosen](mailto:sirosen@globus.org)
551 - [Sunil Kapil](mailto:snlkapil@gmail.com)
552 - [Thom Lu](mailto:thomas.c.lu@gmail.com)
553 - [Tom Christie](mailto:tom@tomchristie.com)
554 - [Tzu-ping Chung](mailto:uranusjr@gmail.com)
555 - [Utsav Shah](mailto:ukshah2@illinois.edu)
557 - [Vishwas B Sharma](mailto:sharma.vishwas88@gmail.com)
558 - [Yngve Høiseth](mailto:yngve@hoiseth.net)
559 - [Yurii Karabas](mailto:1998uriyyo@gmail.com)