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 **[GitHub Actions](#github-actions)** |
40 **[Ignoring unmodified files](#ignoring-unmodified-files)** | **[Used by](#used-by)** |
41 **[Testimonials](#testimonials)** | **[Show your style](#show-your-style)** |
42 **[Contributing](#contributing-to-black)** | **[Change log](#change-log)** |
43 **[Authors](#authors)**
47 ## Installation and usage
51 _Black_ can be installed by running `pip install black`. It requires Python 3.6.0+ to
52 run but you can reformat Python 2 code with it, too.
56 To get started right away with sensible defaults:
59 black {source_file_or_directory}
62 You can run _Black_ as a package if running it as a script doesn't work:
65 python -m black {source_file_or_directory}
68 ### Command line options
70 _Black_ doesn't provide many options. You can list them by running `black --help`:
73 Usage: black [OPTIONS] [SRC]...
75 The uncompromising code formatter.
78 -c, --code TEXT Format the code passed in as a string.
79 -l, --line-length INTEGER How many characters per line to allow.
82 -t, --target-version [py27|py33|py34|py35|py36|py37|py38]
83 Python versions that should be supported by
84 Black's output. [default: per-file auto-
87 --pyi Format all input files like typing stubs
88 regardless of file extension (useful when
89 piping source on standard input).
91 -S, --skip-string-normalization
92 Don't normalize string quotes or prefixes.
93 --check Don't write the files back, just return the
94 status. Return code 0 means nothing would
95 change. Return code 1 means some files
96 would be reformatted. Return code 123 means
97 there was an internal error.
99 --diff Don't write the files back, just output a
100 diff for each file on stdout.
102 --color / --no-color Show colored diff. Only applies when
105 --fast / --safe If --fast given, skip temporary sanity
106 checks. [default: --safe]
108 --include TEXT A regular expression that matches files and
109 directories that should be included on
110 recursive searches. An empty value means
111 all files are included regardless of the
112 name. Use forward slashes for directories
113 on all platforms (Windows, too). Exclusions
114 are calculated first, inclusions later.
117 --exclude TEXT A regular expression that matches files and
118 directories that should be excluded on
119 recursive searches. An empty value means no
120 paths are excluded. Use forward slashes for
121 directories on all platforms (Windows, too).
122 Exclusions are calculated first, inclusions
123 later. [default: /(\.eggs|\.git|\.hg|\.mypy
124 _cache|\.nox|\.tox|\.venv|\.svn|_build|buck-
127 --force-exclude TEXT Like --exclude, but files and directories
128 matching this regex will be excluded even
129 when they are passed explicitly as arguments
131 -q, --quiet Don't emit non-error messages to stderr.
132 Errors are still emitted; silence those with
135 -v, --verbose Also emit messages to stderr about files
136 that were not changed or were ignored due to
139 --version Show the version and exit.
140 --config FILE Read configuration from PATH.
141 -h, --help Show this message and exit.
144 _Black_ is a well-behaved Unix-style command-line tool:
146 - it does nothing if no sources are passed to it;
147 - it will read from standard input and write to standard output if `-` is used as the
149 - it only outputs messages to users on standard error;
150 - exits with code 0 unless an internal error occurred (or `--check` was used).
152 ### Using _Black_ with other tools
154 While _Black_ enforces formatting that conforms to PEP 8, other tools may raise warnings
155 about _Black_'s changes or will overwrite _Black_'s changes. A good example of this is
156 [isort](https://pypi.org/p/isort). Since _Black_ is barely configurable, these tools
157 should be configured to neither warn about nor overwrite _Black_'s changes.
159 Actual details on _Black_ compatible configurations for various tools can be found in
160 [compatible_configs](https://github.com/psf/black/blob/master/docs/compatible_configs.md).
162 ### Migrating your code style without ruining git blame
164 A long-standing argument against moving to automated code formatters like _Black_ is
165 that the migration will clutter up the output of `git blame`. This was a valid argument,
166 but since Git version 2.23, Git natively supports
167 [ignoring revisions in blame](https://git-scm.com/docs/git-blame#Documentation/git-blame.txt---ignore-revltrevgt)
168 with the `--ignore-rev` option. You can also pass a file listing the revisions to ignore
169 using the `--ignore-revs-file` option. The changes made by the revision will be ignored
170 when assigning blame. Lines modified by an ignored revision will be blamed on the
171 previous revision that modified those lines.
173 So when migrating your project's code style to _Black_, reformat everything and commit
174 the changes (preferably in one massive commit). Then put the full 40 characters commit
175 identifier(s) into a file.
178 # Migrate code style to Black
179 5b4ab991dede475d393e9d69ec388fd6bd949699
182 Afterwards, you can pass that file to `git blame` and see clean and meaningful blame
186 $ git blame important.py --ignore-revs-file .git-blame-ignore-revs
187 7a1ae265 (John Smith 2019-04-15 15:55:13 -0400 1) def very_important_function(text, file):
188 abdfd8b0 (Alice Doe 2019-09-23 11:39:32 -0400 2) text = text.lstrip()
189 7a1ae265 (John Smith 2019-04-15 15:55:13 -0400 3) with open(file, "r+") as f:
190 7a1ae265 (John Smith 2019-04-15 15:55:13 -0400 4) f.write(formatted)
193 You can even configure `git` to automatically ignore revisions listed in a file on every
197 $ git config blame.ignoreRevsFile .git-blame-ignore-revs
200 **The one caveat is that GitHub and GitLab do not yet support ignoring revisions using
201 their native UI of blame.** So blame information will be cluttered with a reformatting
202 commit on those platforms. (If you'd like this feature, there's an open issue for
203 [GitLab](https://gitlab.com/gitlab-org/gitlab/-/issues/31423) and please let GitHub
206 ### NOTE: This is a beta product
208 _Black_ is already [successfully used](#used-by) by many projects, small and big. It
209 also sports a decent test suite. However, it is still very new. Things will probably be
210 wonky for a while. This is made explicit by the "Beta" trove classifier, as well as by
211 the "b" in the version number. What this means for you is that **until the formatter
212 becomes stable, you should expect some formatting to change in the future**. That being
213 said, no drastic stylistic changes are planned, mostly responses to bug reports.
215 Also, as a temporary safety measure, _Black_ will check that the reformatted code still
216 produces a valid AST that is equivalent to the original. This slows it down. If you're
217 feeling confident, use `--fast`.
219 ## The _Black_ code style
221 _Black_ is a PEP 8 compliant opinionated formatter. _Black_ reformats entire files in
222 place. It is not configurable. It doesn't take previous formatting into account. Your
223 main option of configuring _Black_ is that it doesn't reformat blocks that start with
224 `# fmt: off` and end with `# fmt: on`. `# fmt: on/off` have to be on the same level of
225 indentation. To learn more about _Black_'s opinions, to go
226 [the_black_code_style](https://github.com/psf/black/blob/master/docs/the_black_code_style.md).
228 Please refer to this document before submitting an issue. What seems like a bug might be
233 Early versions of _Black_ used to be absolutist in some respects. They took after its
234 initial author. This was fine at the time as it made the implementation simpler and
235 there were not many users anyway. Not many edge cases were reported. As a mature tool,
236 _Black_ does make some exceptions to rules it otherwise holds. This
237 [section](https://github.com/psf/black/blob/master/docs/the_black_code_style.md#pragmatism)
238 of `the_black_code_style` describes what those exceptions are and why this is the case.
240 Please refer to this document before submitting an issue just like with the document
241 above. What seems like a bug might be intended behaviour.
245 _Black_ is able to read project-specific default values for its command line options
246 from a `pyproject.toml` file. This is especially useful for specifying custom
247 `--include` and `--exclude` patterns for your project.
249 **Pro-tip**: If you're asking yourself "Do I need to configure anything?" the answer is
250 "No". _Black_ is all about sensible defaults.
252 ### What on Earth is a `pyproject.toml` file?
254 [PEP 518](https://www.python.org/dev/peps/pep-0518/) defines `pyproject.toml` as a
255 configuration file to store build system requirements for Python projects. With the help
256 of tools like [Poetry](https://python-poetry.org/) or
257 [Flit](https://flit.readthedocs.io/en/latest/) it can fully replace the need for
258 `setup.py` and `setup.cfg` files.
260 ### Where _Black_ looks for the file
262 By default _Black_ looks for `pyproject.toml` starting from the common base directory of
263 all files and directories passed on the command line. If it's not there, it looks in
264 parent directories. It stops looking when it finds the file, or a `.git` directory, or a
265 `.hg` directory, or the root of the file system, whichever comes first.
267 If you're formatting standard input, _Black_ will look for configuration starting from
268 the current working directory.
270 You can also explicitly specify the path to a particular file that you want with
271 `--config`. In this situation _Black_ will not look for any other file.
273 If you're running with `--verbose`, you will see a blue message if a file was found and
276 Please note `blackd` will not use `pyproject.toml` configuration.
278 ### Configuration format
280 As the file extension suggests, `pyproject.toml` is a
281 [TOML](https://github.com/toml-lang/toml) file. It contains separate sections for
282 different tools. _Black_ is using the `[tool.black]` section. The option keys are the
283 same as long names of options on the command line.
285 Note that you have to use single-quoted strings in TOML for regular expressions. It's
286 the equivalent of r-strings in Python. Multiline strings are treated as verbose regular
287 expressions by Black. Use `[ ]` to denote a significant space character.
290 <summary>Example `pyproject.toml`</summary>
295 target-version = ['py37']
301 \.eggs # exclude a few common directories in the
302 | \.git # root of the project
312 | foo.py # also separately exclude a file named foo.py in
313 # the root of the project
322 Command-line options have defaults that you can see in `--help`. A `pyproject.toml` can
323 override those defaults. Finally, options provided by the user on the command line
326 _Black_ will only ever use one `pyproject.toml` file during an entire run. It doesn't
327 look for multiple files, and doesn't compose configuration from different levels of the
330 ## Editor integration
332 _Black_ can be integrated into many editors with plugins. They let you run _Black_ on
333 your code with the ease of doing it in your editor. To get started using _Black_ in your
334 editor of choice, please see
335 [editor_integration](https://github.com/psf/black/blob/master/docs/editor_integration.md).
337 Patches are welcome for editors without an editor integration or plugin! More
338 information can be found in
339 [editor_integration](https://github.com/psf/black/blob/master/docs/editor_integration.md#other-editors).
343 `blackd` is a small HTTP server that exposes Black's functionality over a simple
344 protocol. The main benefit of using it is to avoid paying the cost of starting up a new
345 Black process every time you want to blacken a file. Please refer to
346 [blackd](https://github.com/psf/black/blob/master/docs/blackd.md) to get the ball
351 `black-primer` is a tool built for CI (and huumans) to have _Black_ `--check` a number
352 of (configured in `primer.json`) Git accessible projects in parallel.
353 [black_primer](https://github.com/psf/black/blob/master/docs/black_primer.md) has more
354 information regarding its usage and configuration.
356 (A PR adding Mercurial support will be accepted.)
358 ## Version control integration
360 Use [pre-commit](https://pre-commit.com/). Once you
361 [have it installed](https://pre-commit.com/#install), add this to the
362 `.pre-commit-config.yaml` in your repository:
366 - repo: https://github.com/psf/black
370 language_version: python3.6
373 Then run `pre-commit install` and you're ready to go.
375 Avoid using `args` in the hook. Instead, store necessary configuration in
376 `pyproject.toml` so that editors and command-line usage of Black all behave consistently
377 for your project. See _Black_'s own
378 [pyproject.toml](https://github.com/psf/black/blob/master/pyproject.toml) for an
381 If you're already using Python 3.7, switch the `language_version` accordingly. Finally,
382 `stable` is a branch that tracks the latest release on PyPI. If you'd rather run on
383 master, this is also an option.
387 Create a file named `.github/workflows/black.yml` inside your repository with:
392 on: [push, pull_request]
396 runs-on: ubuntu-latest
398 - uses: actions/checkout@v2
399 - uses: actions/setup-python@v2
400 - uses: psf/black@stable
403 ## Ignoring unmodified files
405 _Black_ remembers files it has already formatted, unless the `--diff` flag is used or
406 code is passed via standard input. This information is stored per-user. The exact
407 location of the file depends on the _Black_ version and the system on which _Black_ is
408 run. The file is non-portable. The standard location on common operating systems is:
411 `C:\\Users\<username>\AppData\Local\black\black\Cache\<version>\cache.<line-length>.<file-mode>.pickle`
413 `/Users/<username>/Library/Caches/black/<version>/cache.<line-length>.<file-mode>.pickle`
415 `/home/<username>/.cache/black/<version>/cache.<line-length>.<file-mode>.pickle`
417 `file-mode` is an int flag that determines whether the file was formatted as 3.6+ only,
418 as .pyi, and whether string normalization was omitted.
420 To override the location of these files on macOS or Linux, set the environment variable
421 `XDG_CACHE_HOME` to your preferred location. For example, if you want to put the cache
422 in the directory you're running _Black_ from, set `XDG_CACHE_HOME=.cache`. _Black_ will
423 then write the above files to `.cache/black/<version>/`.
427 The following notable open-source projects trust _Black_ with enforcing a consistent
428 code style: pytest, tox, Pyramid, Django Channels, Hypothesis, attrs, SQLAlchemy,
429 Poetry, PyPA applications (Warehouse, Bandersnatch, Pipenv, virtualenv), pandas, Pillow,
430 every Datadog Agent Integration, Home Assistant.
432 The following organizations use _Black_: Facebook, Dropbox.
434 Are we missing anyone? Let us know.
439 [writer](https://smile.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=dusty+phillips):
441 > _Black_ is opinionated so you don't have to be.
443 **Hynek Schlawack**, [creator of `attrs`](https://www.attrs.org/), core developer of
446 > An auto-formatter that doesn't suck is all I want for Xmas!
448 **Carl Meyer**, [Django](https://www.djangoproject.com/) core developer:
450 > At least the name is good.
452 **Kenneth Reitz**, creator of [`requests`](http://python-requests.org/) and
453 [`pipenv`](https://readthedocs.org/projects/pipenv/):
455 > This vastly improves the formatting of our code. Thanks a ton!
459 Use the badge in your project's README.md:
462 [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
465 Using the badge in README.rst:
468 .. image:: https://img.shields.io/badge/code%20style-black-000000.svg
469 :target: https://github.com/psf/black
473 [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
479 ## Contributing to _Black_
481 In terms of inspiration, _Black_ is about as configurable as _gofmt_. This is
484 Bug reports and fixes are always welcome! However, before you suggest a new feature or
485 configuration knob, ask yourself why you want it. If it enables better integration with
486 some workflow, fixes an inconsistency, speeds things up, and so on - go for it! On the
487 other hand, if your answer is "because I don't like a particular formatting" then you're
488 not ready to embrace _Black_ yet. Such changes are unlikely to get accepted. You can
489 still try but prepare to be disappointed.
491 More details can be found in
492 [CONTRIBUTING](https://github.com/psf/black/blob/master/CONTRIBUTING.md).
496 The log's become rather long. It moved to its own file.
498 See [CHANGES](https://github.com/psf/black/blob/master/CHANGES.md).
502 Glued together by [Łukasz Langa](mailto:lukasz@langa.pl).
504 Maintained with [Carol Willing](mailto:carolcode@willingconsulting.com),
505 [Carl Meyer](mailto:carl@oddbird.net),
506 [Jelle Zijlstra](mailto:jelle.zijlstra@gmail.com),
507 [Mika Naylor](mailto:mail@autophagy.io),
508 [Zsolt Dollenstein](mailto:zsol.zsol@gmail.com), and
509 [Cooper Lees](mailto:me@cooperlees.com).
511 Multiple contributions by:
513 - [Abdur-Rahmaan Janhangeer](mailto:arj.python@gmail.com)
514 - [Adam Johnson](mailto:me@adamj.eu)
515 - [Alexander Huynh](mailto:github@grande.coffee)
516 - [Andrew Thorp](mailto:andrew.thorp.dev@gmail.com)
517 - [Andrey](mailto:dyuuus@yandex.ru)
518 - [Andy Freeland](mailto:andy@andyfreeland.net)
519 - [Anthony Sottile](mailto:asottile@umich.edu)
520 - [Arjaan Buijk](mailto:arjaan.buijk@gmail.com)
521 - [Artem Malyshev](mailto:proofit404@gmail.com)
522 - [Asger Hautop Drewsen](mailto:asgerdrewsen@gmail.com)
523 - [Augie Fackler](mailto:raf@durin42.com)
524 - [Aviskar KC](mailto:aviskarkc10@gmail.com)
525 - [Benjamin Woodruff](mailto:github@benjam.info)
526 - [Brandt Bucher](mailto:brandtbucher@gmail.com)
528 - [Christian Heimes](mailto:christian@python.org)
529 - [Chuck Wooters](mailto:chuck.wooters@microsoft.com)
530 - [Cooper Ry Lees](mailto:me@cooperlees.com)
531 - [Daniel Hahler](mailto:github@thequod.de)
532 - [Daniel M. Capella](mailto:polycitizen@gmail.com)
535 - [Eli Treuherz](mailto:eli@treuherz.com)
536 - [Florent Thiery](mailto:fthiery@gmail.com)
539 - [Ivan Katanić](mailto:ivan.katanic@gmail.com)
540 - [Jason Fried](mailto:me@jasonfried.info)
541 - [jgirardet](mailto:ijkl@netc.fr)
542 - [Joe Antonakakis](mailto:jma353@cornell.edu)
543 - [Jon Dufresne](mailto:jon.dufresne@gmail.com)
544 - [Jonas Obrist](mailto:ojiidotch@gmail.com)
545 - [Josh Bode](mailto:joshbode@fastmail.com)
546 - [Juan Luis Cano Rodríguez](mailto:hello@juanlu.space)
547 - [Katie McLaughlin](mailto:katie@glasnt.com)
549 - [Linus Groh](mailto:mail@linusgroh.de)
550 - [Luka Sterbic](mailto:luka.sterbic@gmail.com)
552 - [Matt VanEseltine](mailto:vaneseltine@gmail.com)
553 - [Michael Flaxman](mailto:michael.flaxman@gmail.com)
554 - [Michael J. Sullivan](mailto:sully@msully.net)
555 - [Michael McClimon](mailto:michael@mcclimon.org)
556 - [Miguel Gaiowski](mailto:miggaiowski@gmail.com)
557 - [Mike](mailto:roshi@fedoraproject.org)
558 - [Min ho Kim](mailto:minho42@gmail.com)
559 - [Miroslav Shubernetskiy](mailto:miroslav@miki725.com)
560 - [Neraste](mailto:neraste.herr10@gmail.com)
561 - [Ofek Lev](mailto:ofekmeister@gmail.com)
562 - [Osaetin Daniel](mailto:osaetindaniel@gmail.com)
563 - [Pablo Galindo](mailto:Pablogsal@gmail.com)
564 - [Peter Bengtsson](mailto:mail@peterbe.com)
567 - [Rishikesh Jha](mailto:rishijha424@gmail.com)
568 - [Stavros Korokithakis](mailto:hi@stavros.io)
569 - [Stephen Rosen](mailto:sirosen@globus.org)
570 - [Sunil Kapil](mailto:snlkapil@gmail.com)
571 - [Thom Lu](mailto:thomas.c.lu@gmail.com)
572 - [Tom Christie](mailto:tom@tomchristie.com)
573 - [Tzu-ping Chung](mailto:uranusjr@gmail.com)
574 - [Utsav Shah](mailto:ukshah2@illinois.edu)
576 - [Vishwas B Sharma](mailto:sharma.vishwas88@gmail.com)
577 - [Yngve Høiseth](mailto:yngve@hoiseth.net)
578 - [Yurii Karabas](mailto:1998uriyyo@gmail.com)