The uncompromising code formatter¶
“Any color you like.”
By using Black, you agree to cede control over minutiae of hand-formatting. In return,
Black gives you speed, determinism, and freedom from pycodestyle
nagging about
formatting. You will save time and mental energy for more important matters.
Black makes code review faster by producing the smallest diffs possible. Blackened code looks the same regardless of the project you’re reading. Formatting becomes transparent after a while and you can focus on the content instead.
Try it out now using the Black Playground.
Note - Black is now stable!
Black is successfully used by many projects, small and big. Black has a comprehensive test suite, with efficient parallel tests, our own auto formatting and parallel Continuous Integration runner. Now that we have become stable, you should not expect large changes to formatting in the future. Stylistic changes will mostly be responses to bug reports and support for new Python syntax.
Also, as a safety measure which slows down processing, Black will check that the
reformatted code still produces a valid AST that is effectively equivalent to the
original (see the
Pragmatism
section for details). If you’re feeling confident, use --fast
.
Testimonials¶
Mike Bayer, author of SQLAlchemy:
I can’t think of any single tool in my entire programming career that has given me a bigger productivity increase by its introduction. I can now do refactorings in about 1% of the keystrokes that it would have taken me previously when we had no way for code to format itself.
Dusty Phillips, writer:
Black is opinionated so you don’t have to be.
Hynek Schlawack, creator of attrs, core developer of Twisted and CPython:
An auto-formatter that doesn’t suck is all I want for Xmas!
Carl Meyer, Django core developer:
At least the name is good.
Kenneth Reitz, creator of requests and pipenv:
This vastly improves the formatting of our code. Thanks a ton!
Show your style¶
Use the badge in your project’s README.md:
[](https://github.com/psf/black)
Using the badge in README.rst:
.. image:: https://img.shields.io/badge/code%20style-black-000000.svg
:target: https://github.com/psf/black
Looks like this:
Contents¶
The Black Code Style¶
The Black code style¶
Code style¶
Black aims for consistency, generality, readability and reducing git diffs. Similar language constructs are formatted with similar rules. Style configuration options are deliberately limited and rarely added. Previous formatting is taken into account as little as possible, with rare exceptions like the magic trailing comma. The coding style used by Black can be viewed as a strict subset of PEP 8.
This document describes the current formatting style. If you’re interested in trying out
where the style is heading, see future style and try running
black --preview
.
How Black wraps lines¶
Black ignores previous formatting and applies uniform horizontal and vertical
whitespace to your code. The rules for horizontal whitespace can be summarized as: do
whatever makes pycodestyle
happy.
As for vertical whitespace, Black tries to render one full expression or simple statement per line. If this fits the allotted line length, great.
# in:
j = [1,
2,
3
]
# out:
j = [1, 2, 3]
If not, Black will look at the contents of the first outer matching brackets and put that in a separate indented line.
# in:
ImportantClass.important_method(exc, limit, lookup_lines, capture_locals, extra_argument)
# out:
ImportantClass.important_method(
exc, limit, lookup_lines, capture_locals, extra_argument
)
If that still doesn’t fit the bill, it will decompose the internal expression further using the same rule, indenting matching brackets every time. If the contents of the matching brackets pair are comma-separated (like an argument list, or a dict literal, and so on) then Black will first try to keep them on the same line with the matching brackets. If that doesn’t work, it will put all of them in separate lines.
# in:
def very_important_function(template: str, *variables, file: os.PathLike, engine: str, header: bool = True, debug: bool = False):
"""Applies `variables` to the `template` and writes to `file`."""
with open(file, 'w') as f:
...
# out:
def very_important_function(
template: str,
*variables,
file: os.PathLike,
engine: str,
header: bool = True,
debug: bool = False,
):
"""Applies `variables` to the `template` and writes to `file`."""
with open(file, "w") as f:
...
If a data structure literal (tuple, list, set, dict) or a line of “from” imports cannot
fit in the allotted length, it’s always split into one element per line. This minimizes
diffs as well as enables readers of code to find which commit introduced a particular
entry. This also makes Black compatible with
isort with the ready-made black
profile or manual configuration.
You might have noticed that closing brackets are always dedented and that a trailing comma is always added. Such formatting produces smaller diffs; when you add or remove an element, it’s always just one line. Also, having the closing bracket dedented provides a clear delimiter between two distinct sections of the code that otherwise share the same indentation level (like the arguments list and the docstring in the example above).
Black prefers parentheses over backslashes, and will remove backslashes if found.
# in:
if some_short_rule1 \
and some_short_rule2:
...
# out:
if some_short_rule1 and some_short_rule2:
...
# in:
if some_long_rule1 \
and some_long_rule2:
...
# out:
if (
some_long_rule1
and some_long_rule2
):
...
Backslashes and multiline strings are one of the two places in the Python grammar that break significant indentation. You never need backslashes, they are used to force the grammar to accept breaks that would otherwise be parse errors. That makes them confusing to look at and brittle to modify. This is why Black always gets rid of them.
If you’re reaching for backslashes, that’s a clear signal that you can do better if you slightly refactor your code. I hope some of the examples above show you that there are many ways in which you can do it.
Line length¶
You probably noticed the peculiar default line length. Black defaults to 88 characters per line, which happens to be 10% over 80. This number was found to produce significantly shorter files than sticking with 80 (the most popular), or even 79 (used by the standard library). In general, 90-ish seems like the wise choice.
If you’re paid by the lines of code you write, you can pass --line-length
with a lower
number. Black will try to respect that. However, sometimes it won’t be able to without
breaking other rules. In those rare cases, auto-formatted code will exceed your allotted
limit.
You can also increase it, but remember that people with sight disabilities find it harder to work with line lengths exceeding 100 characters. It also adversely affects side-by-side diff review on typical screen resolutions. Long lines also make it harder to present code neatly in documentation or talk slides.
Flake8 and other linters¶
See Using Black with other tools about linter compatibility.
Empty lines¶
Black avoids spurious vertical whitespace. This is in the spirit of PEP 8 which says that in-function vertical whitespace should only be used sparingly.
Black will allow single empty lines inside functions, and single and double empty lines on module level left by the original editors, except when they’re within parenthesized expressions. Since such expressions are always reformatted to fit minimal space, this whitespace is lost.
# in:
def function(
some_argument: int,
other_argument: int = 5,
) -> EmptyLineInParenWillBeDeleted:
print("One empty line above me will be kept!")
def this_is_okay_too():
print("No empty line here")
# out:
def function(
some_argument: int,
other_argument: int = 5,
) -> EmptyLineInParenWillBeDeleted:
print("One empty line above me will be kept!")
def this_is_okay_too():
print("No empty line here")
It will also insert proper spacing before and after function definitions. It’s one line before and after inner functions and two lines before and after module-level functions and classes. Black will not put empty lines between function/class definitions and standalone comments that immediately precede the given function/class.
Black will enforce single empty lines between a class-level docstring and the first following field or method. This conforms to PEP 257.
Black won’t insert empty lines after function docstrings unless that empty line is required due to an inner function starting immediately after.
Trailing commas¶
Black will add trailing commas to expressions that are split by comma where each element is on its own line. This includes function signatures.
One exception to adding trailing commas is function signatures containing *
, *args
,
or **kwargs
. In this case a trailing comma is only safe to use on Python 3.6. Black
will detect if your file is already 3.6+ only and use trailing commas in this situation.
If you wonder how it knows, it looks for f-strings and existing use of trailing commas
in function signatures that have stars in them. In other words, if you’d like a trailing
comma in this situation and Black didn’t recognize it was safe to do so, put it there
manually and Black will keep it.
A pre-existing trailing comma informs Black to always explode contents of the current bracket pair into one item per line. Read more about this in the Pragmatism section below.
Strings¶
Black prefers double quotes ("
and """
) over single quotes ('
and '''
). It
will replace the latter with the former as long as it does not result in more backslash
escapes than before.
Black also standardizes string prefixes. Prefix characters are made lowercase with the
exception of capital “R” prefixes, unicode literal markers
(u
) are removed because they are meaningless in Python 3, and in the case of multiple
characters “r” is put first as in spoken language: “raw f-string”.
The main reason to standardize on a single form of quotes is aesthetics. Having one kind of quotes everywhere reduces reader distraction. It will also enable a future version of Black to merge consecutive string literals that ended up on the same line (see #26 for details).
Why settle on double quotes? They anticipate apostrophes in English text. They match the
docstring standard described in
PEP 257. An empty
string in double quotes (""
) is impossible to confuse with a one double-quote
regardless of fonts and syntax highlighting used. On top of this, double quotes for
strings are consistent with C which Python interacts a lot with.
On certain keyboard layouts like US English, typing single quotes is a bit easier than double quotes. The latter requires use of the Shift key. My recommendation here is to keep using whatever is faster to type and let Black handle the transformation.
If you are adopting Black in a large project with pre-existing string conventions
(like the popular
“single quotes for data, double quotes for human-readable strings”),
you can pass --skip-string-normalization
on the command line. This is meant as an
adoption helper, avoid using this for new projects.
Black also processes docstrings. Firstly the indentation of docstrings is corrected for both quotations and the text within, although relative indentation in the text is preserved. Superfluous trailing whitespace on each line and unnecessary new lines at the end of the docstring are removed. All leading tabs are converted to spaces, but tabs inside text are preserved. Whitespace leading and trailing one-line docstrings is removed.
Numeric literals¶
Black standardizes most numeric literals to use lowercase letters for the syntactic
parts and uppercase letters for the digits themselves: 0xAB
instead of 0XAB
and
1e10
instead of 1E10
.
Line breaks & binary operators¶
Black will break a line before a binary operator when splitting a block of code over multiple lines. This is so that Black is compliant with the recent changes in the PEP 8 style guide, which emphasizes that this approach improves readability.
Almost all operators will be surrounded by single spaces, the only exceptions are unary
operators (+
, -
, and ~
), and power operators when both operands are simple. For
powers, an operand is considered simple if it’s only a NAME, numeric CONSTANT, or
attribute access (chained attribute access is allowed), with or without a preceding
unary operator.
# For example, these won't be surrounded by whitespace
a = x**y
b = config.base**5.2
c = config.base**runtime.config.exponent
d = 2**5
e = 2**~5
# ... but these will be surrounded by whitespace
f = 2 ** get_exponent()
g = get_x() ** get_y()
h = config['base'] ** 2
Slices¶
PEP 8
recommends
to treat :
in slices as a binary operator with the lowest priority, and to leave an
equal amount of space on either side, except if a parameter is omitted (e.g.
ham[1 + 1 :]
). It recommends no spaces around :
operators for “simple expressions”
(ham[lower:upper]
), and extra space for “complex expressions”
(ham[lower : upper + offset]
). Black treats anything more than variable names as
“complex” (ham[lower : upper + 1]
). It also states that for extended slices, both :
operators have to have the same amount of spacing, except if a parameter is omitted
(ham[1 + 1 ::]
). Black enforces these rules consistently.
This behaviour may raise E203 whitespace before ':'
warnings in style guide
enforcement tools like Flake8. Since E203
is not PEP 8 compliant, you should tell
Flake8 to ignore these warnings.
Parentheses¶
Some parentheses are optional in the Python grammar. Any expression can be wrapped in a pair of parentheses to form an atom. There are a few interesting cases:
if (...):
while (...):
for (...) in (...):
assert (...), (...)
from X import (...)
assignments like:
target = (...)
target: type = (...)
some, *un, packing = (...)
augmented += (...)
In those cases, parentheses are removed when the entire statement fits in one line, or if the inner expression doesn’t have any delimiters to further split on. If there is only a single delimiter and the expression starts or ends with a bracket, the parentheses can also be successfully omitted since the existing bracket pair will organize the expression neatly anyway. Otherwise, the parentheses are added.
Please note that Black does not add or remove any additional nested parentheses that you might want to have for clarity or further code organization. For example those parentheses are not going to be removed:
return not (this or that)
decision = (maybe.this() and values > 0) or (maybe.that() and values < 0)
Call chains¶
Some popular APIs, like ORMs, use call chaining. This API style is known as a fluent interface. Black formats those by treating dots that follow a call or an indexing operation like a very low priority delimiter. It’s easier to show the behavior than to explain it. Look at the example:
def example(session):
result = (
session.query(models.Customer.id)
.filter(
models.Customer.account_id == account_id,
models.Customer.email == email_address,
)
.order_by(models.Customer.id.asc())
.all()
)
Typing stub files¶
PEP 484 describes the syntax for type hints in Python. One of the use cases for typing is providing type annotations for modules which cannot contain them directly (they might be written in C, or they might be third-party, or their implementation may be overly dynamic, and so on).
To solve this,
stub files with the .pyi
file extension
can be used to describe typing information for an external module. Those stub files omit
the implementation of classes and functions they describe, instead they only contain the
structure of the file (listing globals, functions, and classes with their members). The
recommended code style for those files is more terse than PEP 8:
prefer
...
on the same line as the class/function signature;avoid vertical whitespace between consecutive module-level functions, names, or methods and fields within a single class;
use a single blank line between top-level class definitions, or none if the classes are very small.
Black enforces the above rules. There are additional guidelines for formatting .pyi
file that are not enforced yet but might be in a future version of the formatter:
prefer
...
overpass
;avoid using string literals in type annotations, stub files support forward references natively (like Python 3.7 code with
from __future__ import annotations
);use variable annotations instead of type comments, even for stubs that target older versions of Python.
Line endings¶
Black will normalize line endings (\n
or \r\n
) based on the first line ending of
the file.
Form feed characters¶
Black will retain form feed characters on otherwise empty lines at the module level. Only one form feed is retained for a group of consecutive empty lines. Where there are two empty lines in a row, the form feed is placed on the second line.
Pragmatism¶
Early versions of Black used to be absolutist in some respects. They took after its initial author. This was fine at the time as it made the implementation simpler and there were not many users anyway. Not many edge cases were reported. As a mature tool, Black does make some exceptions to rules it otherwise holds. This section documents what those exceptions are and why this is the case.
The magic trailing comma¶
Black in general does not take existing formatting into account.
However, there are cases where you put a short collection or function call in your code but you anticipate it will grow in the future.
For example:
TRANSLATIONS = {
"en_us": "English (US)",
"pl_pl": "polski",
}
Early versions of Black used to ruthlessly collapse those into one line (it fits!). Now, you can communicate that you don’t want that by putting a trailing comma in the collection yourself. When you do, Black will know to always explode your collection into one item per line.
How do you make it stop? Just delete that trailing comma and Black will collapse your collection into one line if it fits.
If you must, you can recover the behaviour of early versions of Black with the option
--skip-magic-trailing-comma
/ -C
.
r”strings” and R”strings”¶
Black normalizes string quotes as well as string prefixes, making them lowercase. One exception to this rule is r-strings. It turns out that the very popular MagicPython syntax highlighter, used by default by (among others) GitHub and Visual Studio Code, differentiates between r-strings and R-strings. The former are syntax highlighted as regular expressions while the latter are treated as true raw strings with no special semantics.
AST before and after formatting¶
When run with --safe
(the default), Black checks that the code before and after is
semantically equivalent. This check is done by comparing the AST of the source with the
AST of the target. There are three limited cases in which the AST does differ:
Black cleans up leading and trailing whitespace of docstrings, re-indenting them if needed. It’s been one of the most popular user-reported features for the formatter to fix whitespace issues with docstrings. While the result is technically an AST difference, due to the various possibilities of forming docstrings, all real-world uses of docstrings that we’re aware of sanitize indentation and leading/trailing whitespace anyway.
Black manages optional parentheses for some statements. In the case of the
del
statement, presence of wrapping parentheses or lack of thereof changes the resulting AST but is semantically equivalent in the interpreter.Black might move comments around, which includes type comments. Those are part of the AST as of Python 3.8. While the tool implements a number of special cases for those comments, there is no guarantee they will remain where they were in the source. Note that this doesn’t change runtime behavior of the source code.
To put things in perspective, the code equivalence check is a feature of Black which other formatters don’t implement at all. It is of crucial importance to us to ensure code behaves the way it did before it got reformatted. We treat this as a feature and there are no plans to relax this in the future. The exceptions enumerated above stem from either user feedback or implementation details of the tool. In each case we made due diligence to ensure that the AST divergence is of no practical consequence.
The (future of the) Black code style¶
Preview style¶
Experimental, potentially disruptive style changes are gathered under the --preview
CLI flag. At the end of each year, these changes may be adopted into the default style,
as described in The Black Code Style. Because the functionality is
experimental, feedback and issue reports are highly encouraged!
In the past, the preview style included some features with known bugs, so that we were
unable to move these features to the stable style. Therefore, such features are now
moved to the --unstable
style. All features in the --preview
style are expected to
make it to next year’s stable style; features in the --unstable
style will be
stabilized only if issues with them are fixed. If bugs are discovered in a --preview
feature, it is demoted to the --unstable
style. To avoid thrash when a feature is
demoted from the --preview
to the --unstable
style, users can use the
--enable-unstable-feature
flag to enable specific unstable features.
Currently, the following features are included in the preview style:
hex_codes_in_unicode_sequences
: normalize casing of Unicode escape characters in stringsunify_docstring_detection
: fix inconsistencies in whether certain strings are detected as docstringsno_normalize_fmt_skip_whitespace
: whitespace before# fmt: skip
comments is no longer normalizedtyped_params_trailing_comma
: consistently add trailing commas to typed function parametersis_simple_lookup_for_doublestar_expression
: fix line length computation for certain expressions that involve the power operatordocstring_check_for_newline
: checks if there is a newline before the terminating quotes of a docstringremove_redundant_guard_parens
: Removes redundant parentheses inif
guards forcase
blocks.parens_for_long_if_clauses_in_case_block
: Adds parentheses toif
clauses incase
blocks when the line is too long
The unstable style additionally includes the following features:
string_processing
: split long string literals and related changes (see below)wrap_long_dict_values_in_parens
: add parentheses to long values in dictionaries (see below)multiline_string_handling
: more compact formatting of expressions involving multiline strings (see below)hug_parens_with_braces_and_square_brackets
: more compact formatting of nested brackets (see below)
Improved multiline dictionary and list indentation for sole function parameter¶
For better readability and less verticality, Black now pairs parentheses (“(”, “)”) with braces (“{”, “}”) and square brackets (“[”, “]”) on the same line. For example:
foo(
[
1,
2,
3,
]
)
nested_array = [
[
1,
2,
3,
]
]
will be changed to:
foo([
1,
2,
3,
])
nested_array = [[
1,
2,
3,
]]
This also applies to list and dictionary unpacking:
foo(
*[
a_long_function_name(a_long_variable_name)
for a_long_variable_name in some_generator
]
)
will become:
foo(*[
a_long_function_name(a_long_variable_name)
for a_long_variable_name in some_generator
])
You can use a magic trailing comma to avoid this compacting behavior; by default, Black will not reformat the following code:
foo(
[
1,
2,
3,
],
)
Improved string processing¶
Black will split long string literals and merge short ones. Parentheses are used where appropriate. When split, parts of f-strings that don’t need formatting are converted to plain strings. User-made splits are respected when they do not exceed the line length limit. Line continuation backslashes are converted into parenthesized strings. Unnecessary parentheses are stripped. The stability and status of this feature is tracked in this issue.
Improved parentheses management in dicts¶
For dict literals with long values, they are now wrapped in parentheses. Unnecessary parentheses are now removed. For example:
my_dict = {
"a key in my dict": a_very_long_variable
* and_a_very_long_function_call()
/ 100000.0,
"another key": (short_value),
}
will be changed to:
my_dict = {
"a key in my dict": (
a_very_long_variable * and_a_very_long_function_call() / 100000.0
),
"another key": short_value,
}
Improved multiline string handling¶
Black is smarter when formatting multiline strings, especially in function arguments, to avoid introducing extra line breaks. Previously, it would always consider multiline strings as not fitting on a single line. With this new feature, Black looks at the context around the multiline string to decide if it should be inlined or split to a separate line. For example, when a multiline string is passed to a function, Black will only split the multiline string if a line is too long or if multiple arguments are being passed.
For example, Black will reformat
textwrap.dedent(
"""\
This is a
multiline string
"""
)
to:
textwrap.dedent("""\
This is a
multiline string
""")
And:
MULTILINE = """
foobar
""".replace(
"\n", ""
)
to:
MULTILINE = """
foobar
""".replace("\n", "")
Implicit multiline strings are special, because they can have inline comments. Strings without comments are merged, for example
s = (
"An "
"implicit "
"multiline "
"string"
)
becomes
s = "An implicit multiline string"
A comment on any line of the string (or between two string lines) will block the merging, so
s = (
"An " # Important comment concerning just this line
"implicit "
"multiline "
"string"
)
and
s = (
"An "
"implicit "
# Comment in between
"multiline "
"string"
)
will not be merged. Having the comment after or before the string lines (but still inside the parens) will merge the string. For example
s = ( # Top comment
"An "
"implicit "
"multiline "
"string"
# Bottom comment
)
becomes
s = ( # Top comment
"An implicit multiline string"
# Bottom comment
)
Potential future changes¶
This section lists changes that we may want to make in the future, but that aren’t implemented yet.
Using backslashes for with statements¶
Backslashes are bad and should be never be used however
there is one exception: with
statements using multiple context managers. Before Python
3.9 Python’s grammar does not allow organizing parentheses around the series of context
managers.
We don’t want formatting like:
with make_context_manager1() as cm1, make_context_manager2() as cm2, make_context_manager3() as cm3, make_context_manager4() as cm4:
... # nothing to split on - line too long
So Black will, when we implement this, format it like this:
with \
make_context_manager1() as cm1, \
make_context_manager2() as cm2, \
make_context_manager3() as cm3, \
make_context_manager4() as cm4 \
:
... # backslashes and an ugly stranded colon
Although when the target version is Python 3.9 or higher, Black uses parentheses
instead in --preview
mode (see below) since they’re allowed in Python 3.9 and higher.
An alternative to consider if the backslashes in the above formatting are undesirable is
to use contextlib.ExitStack
to combine context managers in the
following way:
with contextlib.ExitStack() as exit_stack:
cm1 = exit_stack.enter_context(make_context_manager1())
cm2 = exit_stack.enter_context(make_context_manager2())
cm3 = exit_stack.enter_context(make_context_manager3())
cm4 = exit_stack.enter_context(make_context_manager4())
...
Black is a PEP 8 compliant opinionated formatter with its own style.
While keeping the style unchanged throughout releases has always been a goal, the Black code style isn’t set in stone. It evolves to accommodate for new features in the Python language and, occasionally, in response to user feedback. Large-scale style preferences presented in The Black code style are very unlikely to change, but minor style aspects and details might change according to the stability policy presented below. Ongoing style considerations are tracked on GitHub with the style issue label.
Stability Policy¶
The following policy applies for the Black code style, in non pre-release versions of Black:
If code has been formatted with Black, it will remain unchanged when formatted with the same options using any other release in the same calendar year.
This means projects can safely use
black ~= 22.0
without worrying about formatting changes disrupting their project in 2022. We may still fix bugs where Black crashes on some code, and make other improvements that do not affect formatting.In rare cases, we may make changes affecting code that has not been previously formatted with Black. For example, we have had bugs where we accidentally removed some comments. Such bugs can be fixed without breaking the stability policy.
The first release in a new calendar year may contain formatting changes, although these will be minimised as much as possible. This is to allow for improved formatting enabled by newer Python language syntax as well as due to improvements in the formatting logic.
The
--preview
and--unstable
flags are exempt from this policy. There are no guarantees around the stability of the output with these flags passed into Black. They are intended for allowing experimentation with proposed changes to the Black code style. The--preview
style at the end of a year should closely match the stable style for the next year, but we may always make changes.
Documentation for both the current and future styles can be found:
Getting Started¶
New to Black? Don’t worry, you’ve found the perfect place to get started!
Do you like the Black code style?¶
Before using Black on some of your code, it might be a good idea to first understand how Black will format your code. Black isn’t for everyone and you may find something that is a dealbreaker for you personally, which is okay! The current Black code style is described here.
Try it out online¶
Also, you can try out Black online for minimal fuss on the Black Playground generously created by José Padilla.
Installation¶
Black can be installed by running pip install black
. It requires Python 3.8+ to run.
If you want to format Jupyter Notebooks, install with pip install "black[jupyter]"
.
If you use pipx, you can install Black with pipx install black
.
If you can’t wait for the latest hotness and want to install from GitHub, use:
pip install git+https://github.com/psf/black
Basic usage¶
To get started right away with sensible defaults:
black {source_file_or_directory}...
You can run Black as a package if running it as a script doesn’t work:
python -m black {source_file_or_directory}...
Next steps¶
Took a look at the Black code style and tried out Black? Fantastic, you’re ready for more. Why not explore some more on using Black by reading Usage and Configuration: The basics. Alternatively, you can check out the Introducing Black to your project guide.
Usage and Configuration¶
The basics¶
Foundational knowledge on using and configuring Black.
Black is a well-behaved Unix-style command-line tool:
it does nothing if it finds no sources to format;
it will read from standard input and write to standard output if
-
is used as the filename;it only outputs messages to users on standard error;
exits with code 0 unless an internal error occurred or a CLI option prompted it.
Usage¶
Black will reformat entire files in place. To get started right away with sensible defaults:
black {source_file_or_directory}
You can run Black as a package if running it as a script doesn’t work:
python -m black {source_file_or_directory}
Ignoring sections¶
Black will not reformat lines that contain # fmt: skip
or blocks that start with
# fmt: off
and end with # fmt: on
. # fmt: skip
can be mixed with other
pragmas/comments either with multiple comments (e.g. # fmt: skip # pylint # noqa
) or
as a semicolon separated list (e.g. # fmt: skip; pylint; noqa
). # fmt: on/off
must
be on the same level of indentation and in the same block, meaning no unindents beyond
the initial indentation level between them. Black also recognizes
YAPF’s block comments to the same effect, as a
courtesy for straddling code.
Command line options¶
The CLI options of Black can be displayed by running black --help
. All options are
also covered in more detail below.
While Black has quite a few knobs these days, it is still opinionated so style options are deliberately limited and rarely added.
Note that all command-line options listed above can also be configured using a
pyproject.toml
file (more on that below).
-h
, --help
¶
Show available command-line options and exit.
-c
, --code
¶
Format the code passed in as a string.
$ black --code "print ( 'hello, world' )"
print("hello, world")
-l
, --line-length
¶
How many characters per line to allow. The default is 88.
See also the style documentation.
-t
, --target-version
¶
Python versions that should be supported by Black’s output. You can run black --help
and look for the --target-version
option to see the full list of supported versions.
You should include all versions that your code supports. If you support Python 3.8
through 3.11, you should write:
$ black -t py38 -t py39 -t py310 -t py311
In a configuration file, you can write:
target-version = ["py38", "py39", "py310", "py311"]
By default, Black will infer target versions from the project metadata in
pyproject.toml
, specifically the [project.requires-python]
field. If this does not
yield conclusive results, Black will use per-file auto-detection.
Black uses this option to decide what grammar to use to parse your code. In addition,
it may use it to decide what style to use. For example, support for a trailing comma
after *args
in a function call was added in Python 3.5, so Black will add this comma
only if the target versions are all Python 3.5 or higher:
$ black --line-length=10 --target-version=py35 -c 'f(a, *args)'
f(
a,
*args,
)
$ black --line-length=10 --target-version=py34 -c 'f(a, *args)'
f(
a,
*args
)
$ black --line-length=10 --target-version=py34 --target-version=py35 -c 'f(a, *args)'
f(
a,
*args
)
--pyi
¶
Format all input files like typing stubs regardless of file extension. This is useful when piping source on standard input.
--ipynb
¶
Format all input files like Jupyter Notebooks regardless of file extension. This is useful when piping source on standard input.
--python-cell-magics
¶
When processing Jupyter Notebooks, add the given magic to the list of known python- magics. Useful for formatting cells with custom python magics.
-x, --skip-source-first-line
¶
Skip the first line of the source code.
-S, --skip-string-normalization
¶
By default, Black uses double quotes for all strings and normalizes string prefixes, as described in the style documentation. If this option is given, strings are left unchanged instead.
-C, --skip-magic-trailing-comma
¶
By default, Black uses existing trailing commas as an indication that short lines should be left separate, as described in the style documentation. If this option is given, the magic trailing comma is ignored.
--preview
¶
Enable potentially disruptive style changes that we expect to add to Black’s main functionality in the next major release. Use this if you want a taste of what next year’s style will look like.
Read more about our preview style.
There is no guarantee on the code style produced by this flag across releases.
--unstable
¶
Enable all style changes in --preview
, plus additional changes that we would like to
make eventually, but that have known issues that need to be fixed before they can move
back to the --preview
style. Use this if you want to experiment with these changes and
help fix issues with them.
There is no guarantee on the code style produced by this flag across releases.
--enable-unstable-feature
¶
Enable specific features from the --unstable
style. See
the preview style documentation for the list of supported
features. This flag can only be used when --preview
is enabled. Users are encouraged
to use this flag if they use --preview
style and a feature that affects their code is
moved from the --preview
to the --unstable
style, but they want to avoid the thrash
from undoing this change.
There are no guarantees on the behavior of these features, or even their existence, across releases.
--check
¶
Don’t write the files back, just return the status. Black will exit with:
code 0 if nothing would change;
code 1 if some files would be reformatted; or
code 123 if there was an internal error
If used in combination with --quiet
then only the exit code will be returned, unless
there was an internal error.
$ black test.py --check
All done! ✨ 🍰 ✨
1 file would be left unchanged.
$ echo $?
0
$ black test.py --check
would reformat test.py
Oh no! 💥 💔 💥
1 file would be reformatted.
$ echo $?
1
$ black test.py --check
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
Oh no! 💥 💔 💥
1 file would fail to reformat.
$ echo $?
123
--diff
¶
Don’t write the files back, just output a diff to indicate what changes Black would’ve made. They are printed to stdout so capturing them is simple.
If you’d like colored diffs, you can enable them with --color
.
$ black test.py --diff
--- test.py 2021-03-08 22:23:40.848954+00:00
+++ test.py 2021-03-08 22:23:47.126319+00:00
@@ -1 +1 @@
-print ( 'hello, world' )
+print("hello, world")
would reformat test.py
All done! ✨ 🍰 ✨
1 file would be reformatted.
--color
/ --no-color
¶
Show (or do not show) colored diff. Only applies when --diff
is given.
--line-ranges
¶
When specified, Black will try its best to only format these lines.
This option can be specified multiple times, and a union of the lines will be formatted.
Each range must be specified as two integers connected by a -
: <START>-<END>
. The
<START>
and <END>
integer indices are 1-based and inclusive on both ends.
Black may still format lines outside of the ranges for multi-line statements.
Formatting more than one file or any ipynb files with this option is not supported. This
option cannot be specified in the pyproject.toml
config.
Example: black --line-ranges=1-10 --line-ranges=21-30 test.py
will format lines from
1
to 10
and 21
to 30
.
This option is mainly for editor integrations, such as “Format Selection”.
Note
Due to #4052, --line-ranges
might format
extra lines outside of the ranges when ther are unformatted lines with the exact
content. It also disables Black’s formatting stability check in --safe
mode.
--fast
/ --safe
¶
By default, Black performs an AST safety check after formatting
your code. The --fast
flag turns off this check and the --safe
flag explicitly
enables it.
--required-version
¶
Require a specific version of Black to be running. This is useful for ensuring that all contributors to your project are using the same version, because different versions of Black may format code a little differently. This option can be set in a configuration file for consistent results across environments.
$ black --version
black, 24.4.2 (compiled: yes)
$ black --required-version 24.4.2 -c "format = 'this'"
format = "this"
$ black --required-version 31.5b2 -c "still = 'beta?!'"
Oh no! 💥 💔 💥 The required version does not match the running version!
You can also pass just the major version:
$ black --required-version 22 -c "format = 'this'"
format = "this"
$ black --required-version 31 -c "still = 'beta?!'"
Oh no! 💥 💔 💥 The required version does not match the running version!
Because of our stability policy, this will guarantee stable formatting, but still allow you to take advantage of improvements that do not affect formatting.
--exclude
¶
A regular expression that matches files and directories that should be excluded on
recursive searches. An empty value means no paths are excluded. Use forward slashes for
directories on all platforms (Windows, too). By default, Black also ignores all paths
listed in .gitignore
. Changing this value will override all default exclusions.
If the regular expression contains newlines, it is treated as a
verbose regular expression. This
is typically useful when setting these options in a pyproject.toml
configuration file;
see Configuration format for more information.
--extend-exclude
¶
Like --exclude
, but adds additional files and directories on top of the default values
instead of overriding them.
--force-exclude
¶
Like --exclude
, but files and directories matching this regex will be excluded even
when they are passed explicitly as arguments. This is useful when invoking Black
programmatically on changed files, such as in a pre-commit hook or editor plugin.
--stdin-filename
¶
The name of the file when passing it through stdin. Useful to make sure Black will
respect the --force-exclude
option on some editors that rely on using stdin.
--include
¶
A regular expression that matches files and directories that should be included on
recursive searches. An empty value means all files are included regardless of the name.
Use forward slashes for directories on all platforms (Windows, too). Overrides all
exclusions, including from .gitignore
and command line options.
-W
, --workers
¶
When Black formats multiple files, it may use a process pool to speed up formatting.
This option controls the number of parallel workers. This can also be specified via the
BLACK_NUM_WORKERS
environment variable. Defaults to the number of CPUs in the system.
-q
, --quiet
¶
Stop emitting all non-critical output. Error messages will still be emitted (which can
silenced by 2>/dev/null
).
$ black src/ -q
error: cannot format src/black_primer/cli.py: Cannot parse: 5:6: mport asyncio
-v
, --verbose
¶
Emit messages about files that were not changed or were ignored due to exclusion patterns. If Black is using a configuration file, a message detailing which one it is using will be emitted.
$ black src/ -v
Using configuration from /tmp/pyproject.toml.
src/blib2to3 ignored: matches the --extend-exclude regular expression
src/_black_version.py wasn't modified on disk since last run.
src/black/__main__.py wasn't modified on disk since last run.
error: cannot format src/black_primer/cli.py: Cannot parse: 5:6: mport asyncio
reformatted src/black_primer/lib.py
reformatted src/blackd/__init__.py
reformatted src/black/__init__.py
Oh no! 💥 💔 💥
3 files reformatted, 2 files left unchanged, 1 file failed to reformat
--version
¶
You can check the version of Black you have installed using the --version
flag.
$ black --version
black, 24.4.2
--config
¶
Read configuration options from a configuration file. See below for more details on the configuration file.
Environment variable options¶
Black supports the following configuration via environment variables.
BLACK_CACHE_DIR
¶
The directory where Black should store its cache.
BLACK_NUM_WORKERS
¶
The number of parallel workers Black should use. The command line option -W
/
--workers
takes precedence over this environment variable.
Code input alternatives¶
Black supports formatting code via stdin, with the result being printed to stdout.
Just let Black know with -
as the path.
$ echo "print ( 'hello, world' )" | black -
print("hello, world")
reformatted -
All done! ✨ 🍰 ✨
1 file reformatted.
Tip: if you need Black to treat stdin input as a file passed directly via the CLI,
use --stdin-filename
. Useful to make sure Black will respect the --force-exclude
option on some editors that rely on using stdin.
You can also pass code as a string using the --code
option.
Writeback and reporting¶
By default Black reformats the files given and/or found in place. Sometimes you need Black to just tell you what it would do without actually rewriting the Python files.
There’s two variations to this mode that are independently enabled by their respective flags:
--check
(exit with code 1 if any file would be reformatted)--diff
(print a diff instead of reformatting files)
Both variations can be enabled at once.
Output verbosity¶
Black in general tries to produce the right amount of output, balancing between usefulness and conciseness. By default, Black emits files modified and error messages, plus a short summary.
$ black src/
error: cannot format src/black_primer/cli.py: Cannot parse: 5:6: mport asyncio
reformatted src/black_primer/lib.py
reformatted src/blackd/__init__.py
reformatted src/black/__init__.py
Oh no! 💥 💔 💥
3 files reformatted, 2 files left unchanged, 1 file failed to reformat.
The --quiet
and --verbose
flags control output verbosity.
Configuration via a file¶
Black is able to read project-specific default values for its command line options
from a pyproject.toml
file. This is especially useful for specifying custom
--include
and --exclude
/--force-exclude
/--extend-exclude
patterns for your
project.
Pro-tip: If you’re asking yourself “Do I need to configure anything?” the answer is “No”. Black is all about sensible defaults. Applying those defaults will have your code in compliance with many other Black formatted projects.
What on Earth is a pyproject.toml
file?¶
PEP 518 defines pyproject.toml
as a
configuration file to store build system requirements for Python projects. With the help
of tools like Poetry,
Flit, or
Hatch it can fully replace the need for setup.py
and
setup.cfg
files.
Where Black looks for the file¶
By default Black looks for pyproject.toml
containing a [tool.black]
section
starting from the common base directory of all files and directories passed on the
command line. If it’s not there, it looks in parent directories. It stops looking when
it finds the file, or a .git
directory, or a .hg
directory, or the root of the file
system, whichever comes first.
If you’re formatting standard input, Black will look for configuration starting from the current working directory.
You can use a “global” configuration, stored in a specific location in your home directory. This will be used as a fallback configuration, that is, it will be used if and only if Black doesn’t find any configuration as mentioned above. Depending on your operating system, this configuration file should be stored as:
Windows:
~\.black
Unix-like (Linux, MacOS, etc.):
$XDG_CONFIG_HOME/black
(~/.config/black
if theXDG_CONFIG_HOME
environment variable is not set)
Note that these are paths to the TOML file itself (meaning that they shouldn’t be named
as pyproject.toml
), not directories where you store the configuration. Here, ~
refers to the path to your home directory. On Windows, this will be something like
C:\\Users\UserName
.
You can also explicitly specify the path to a particular file that you want with
--config
. In this situation Black will not look for any other file.
If you’re running with --verbose
, you will see a message if a file was found and used.
Please note blackd
will not use pyproject.toml
configuration.
Configuration format¶
As the file extension suggests, pyproject.toml
is a
TOML file. It contains separate sections for
different tools. Black is using the [tool.black]
section. The option keys are the
same as long names of options on the command line.
Note that you have to use single-quoted strings in TOML for regular expressions. It’s
the equivalent of r-strings in Python. Multiline strings are treated as verbose regular
expressions by Black. Use [ ]
to denote a significant space character.
Example pyproject.toml
[tool.black]
line-length = 88
target-version = ['py37']
include = '\.pyi?$'
# 'extend-exclude' excludes files or directories in addition to the defaults
extend-exclude = '''
# A regex preceded with ^/ will apply only to files and directories
# in the root of the project.
(
^/foo.py # exclude a file named foo.py in the root of the project
| .*_pb2.py # exclude autogenerated Protocol Buffer files anywhere in the project
)
'''
Lookup hierarchy¶
Command-line options have defaults that you can see in --help
. A pyproject.toml
can
override those defaults. Finally, options provided by the user on the command line
override both.
Black will only ever use one pyproject.toml
file during an entire run. It doesn’t
look for multiple files, and doesn’t compose configuration from different levels of the
file hierarchy.
Next steps¶
A good next step would be configuring auto-discovery so black .
is all you need
instead of laborously listing every file or directory. You can get started by heading
over to File collection and discovery.
Another good choice would be setting up an integration with your editor of choice or with pre-commit for source version control.
File collection and discovery¶
You can directly pass Black files, but you can also pass directories and Black will walk them, collecting files to format. It determines what files to format or skip automatically using the inclusion and exclusion regexes and as well their modification time.
Ignoring unmodified files¶
Black remembers files it has already formatted, unless the --diff
flag is used or
code is passed via standard input. This information is stored per-user. The exact
location of the file depends on the Black version and the system on which Black is
run. The file is non-portable. The standard location on common operating systems is:
Windows:
C:\\Users\<username>\AppData\Local\black\black\Cache\<version>\cache.<line-length>.<file-mode>.pickle
macOS:
/Users/<username>/Library/Caches/black/<version>/cache.<line-length>.<file-mode>.pickle
Linux:
/home/<username>/.cache/black/<version>/cache.<line-length>.<file-mode>.pickle
file-mode
is an int flag that determines whether the file was formatted as 3.6+ only,
as .pyi, and whether string normalization was omitted.
To override the location of these files on all systems, set the environment variable
BLACK_CACHE_DIR
to the preferred location. Alternatively on macOS and Linux, set
XDG_CACHE_HOME
to your preferred location. For example, if you want to put the cache
in the directory you’re running Black from, set BLACK_CACHE_DIR=.cache/black
.
Black will then write the above files to .cache/black
. Note that BLACK_CACHE_DIR
will take precedence over XDG_CACHE_HOME
if both are set.
.gitignore¶
If --exclude
is not set, Black will automatically ignore files and directories in
.gitignore
file(s), if present.
If you want Black to continue using .gitignore
while also configuring the exclusion
rules, please use --extend-exclude
.
Black as a server (blackd)¶
blackd
is a small HTTP server that exposes Black’s functionality over a simple
protocol. The main benefit of using it is to avoid the cost of starting up a new Black
process every time you want to blacken a file.
Warning
blackd
should not be run as a publicly accessible server as there are no security
precautions in place to prevent abuse. It is intended for local use only.
Usage¶
blackd
is not packaged alongside Black by default because it has additional
dependencies. You will need to execute pip install 'black[d]'
to install it.
You can start the server on the default port, binding only to the local interface by
running blackd
. You will see a single line mentioning the server’s version, and the
host and port it’s listening on. blackd
will then print an access log similar to most
web servers on standard output, merged with any exception traces caused by invalid
formatting requests.
blackd
provides even less options than Black. You can see them by running
blackd --help
:
Usage: blackd [OPTIONS]
Options:
--bind-host TEXT Address to bind the server to. [default: localhost]
--bind-port INTEGER Port to listen on [default: 45484]
--version Show the version and exit.
-h, --help Show this message and exit.
There is no official blackd
client tool (yet!). You can test that blackd is working
using curl
:
blackd --bind-port 9090 & # or let blackd choose a port
curl -s -XPOST "localhost:9090" -d "print('valid')"
Protocol¶
blackd
only accepts POST
requests at the /
path. The body of the request should
contain the python source code to be formatted, encoded according to the charset
field
in the Content-Type
request header. If no charset
is specified, blackd
assumes
UTF-8
.
There are a few HTTP headers that control how the source code is formatted. These
correspond to command line flags for Black. There is one exception to this:
X-Protocol-Version
which if present, should have the value 1
, otherwise the request
is rejected with HTTP 501
(Not Implemented).
The headers controlling how source code is formatted are:
X-Line-Length
: corresponds to the--line-length
command line flag.X-Skip-Source-First-Line
: corresponds to the--skip-source-first-line
command line flag. If present and its value is not an empty string, the first line of the source code will be ignored.X-Skip-String-Normalization
: corresponds to the--skip-string-normalization
command line flag. If present and its value is not the empty string, no string normalization will be performed.X-Skip-Magic-Trailing-Comma
: corresponds to the--skip-magic-trailing-comma
command line flag. If present and its value is not an empty string, trailing commas will not be used as a reason to split lines.X-Preview
: corresponds to the--preview
command line flag. If present and its value is not an empty string, experimental and potentially disruptive style changes will be used.X-Unstable
: corresponds to the--unstable
command line flag. If present and its value is not an empty string, experimental style changes that are known to be buggy will be used.X-Enable-Unstable-Feature
: corresponds to the--enable-unstable-feature
flag. The contents of the flag must be a comma-separated list of unstable features to be enabled. Example:X-Enable-Unstable-Feature: feature1, feature2
.X-Fast-Or-Safe
: if set tofast
,blackd
will act as Black does when passed the--fast
command line flag.X-Python-Variant
: if set topyi
,blackd
will act as Black does when passed the--pyi
command line flag. Otherwise, its value must correspond to a Python version or a set of comma-separated Python versions, optionally prefixed withpy
. For example, to request code that is compatible with Python 3.5 and 3.6, set the header topy3.5,py3.6
.X-Diff
: corresponds to the--diff
command line flag. If present, a diff of the formats will be output.
If any of these headers are set to invalid values, blackd
returns a HTTP 400
error
response, mentioning the name of the problematic header in the message body.
Apart from the above, blackd
can produce the following response codes:
HTTP 204
: If the input is already well-formatted. The response body is empty.HTTP 200
: If formatting was needed on the input. The response body contains the blackened Python code, and theContent-Type
header is set accordingly.HTTP 400
: If the input contains a syntax error. Details of the error are returned in the response body.HTTP 500
: If there was any other kind of error while trying to format the input. The response body contains a textual representation of the error.
The response headers include a X-Black-Version
header containing the version of
Black.
Black Docker image¶
Official Black Docker images are available on Docker Hub.
Black images with the following tags are available:
release numbers, e.g.
21.5b2
,21.6b0
,21.7b0
etc.
ℹ Recommended for users who want to use a particular version of Black.latest_release
- tag created when a new version of Black is released.
ℹ Recommended for users who want to use released versions of Black. It maps to the latest release of Black.latest_prerelease
- tag created when a new alpha (prerelease) version of Black is released.
ℹ Recommended for users who want to preview or test alpha versions of Black. Note that the most recent release may be newer than any prerelease, because no prereleases are created before most releases.latest
- tag used for the newest image of Black.
ℹ Recommended for users who always want to use the latest version of Black, even before it is released.
There is one more tag used for Black Docker images - latest_non_release
. It is
created for all unreleased
commits on the main
branch. This tag is
not meant to be used by external users.
From version 23.11.0 the Docker image installs a compiled black into the image.
Usage¶
A permanent container doesn’t have to be created to use Black as a Docker image. It’s
enough to run Black commands for the chosen image denoted as :tag
. In the below
examples, the latest_release
tag is used. If :tag
is omitted, the latest
tag will
be used.
More about Black usage can be found in Usage and Configuration: The basics.
Check Black version¶
$ docker run --rm pyfound/black:latest_release black --version
Check code¶
$ docker run --rm --volume $(pwd):/src --workdir /src pyfound/black:latest_release black --check .
Remark: besides regular Black exit codes returned by --check
option, Docker exit codes
should also be considered.
Sometimes, running Black with its defaults and passing filepaths to it just won’t cut it. Passing each file using paths will become burdensome, and maybe you would like Black to not touch your files and just output diffs. And yes, you can tweak certain parts of Black’s style, but please know that configurability in this area is purposefully limited.
Using many of these more advanced features of Black will require some configuration. Configuration that will either live on the command line or in a TOML configuration file.
This section covers features of Black and configuring Black in detail:
Integrations¶
Editor integration¶
Emacs¶
Options include the following:
PyCharm/IntelliJ IDEA¶
There are several different ways you can use Black from PyCharm:
Using the built-in Black integration (PyCharm 2023.2 and later). This option is the simplest to set up.
As local server using the BlackConnect plugin. This option formats the fastest. It spins up Black’s HTTP server, to avoid the startup cost on subsequent formats.
As external tool.
As file watcher.
Built-in Black integration¶
Install
black
.$ pip install black
Go to
Preferences or Settings -> Tools -> Black
and configure Black to your liking.
As local server¶
Install Black with the
d
extra.$ pip install 'black[d]'
Install BlackConnect IntelliJ IDEs plugin.
Open plugin configuration in PyCharm/IntelliJ IDEA
On macOS:
PyCharm -> Preferences -> Tools -> BlackConnect
On Windows / Linux / BSD:
File -> Settings -> Tools -> BlackConnect
In
Local Instance (shared between projects)
section:Check
Start local blackd instance when plugin loads
.Press the
Detect
button nearPath
input. The plugin should detect theblackd
executable.
In
Trigger Settings
section checkTrigger on code reformat
to enable code reformatting with Black.Format the currently opened file by selecting
Code -> Reformat Code
or using a shortcut.Optionally, to run Black on every file save:
In
Trigger Settings
section of plugin configuration checkTrigger when saving changed files
.
As external tool¶
Install
black
.$ pip install black
Locate your
black
installation folder.On macOS / Linux / BSD:
$ which black /usr/local/bin/black # possible location
On Windows:
$ where black %LocalAppData%\Programs\Python\Python36-32\Scripts\black.exe # possible location
Note that if you are using a virtual environment detected by PyCharm, this is an unneeded step. In this case the path to
black
is$PyInterpreterDirectory$/black
.Open External tools in PyCharm/IntelliJ IDEA
On macOS:
PyCharm -> Preferences -> Tools -> External Tools
On Windows / Linux / BSD:
File -> Settings -> Tools -> External Tools
Click the + icon to add a new external tool with the following values:
Name: Black
Description: Black is the uncompromising Python code formatter.
Program: <install_location_from_step_2>
Arguments:
"$FilePath$"
Format the currently opened file by selecting
Tools -> External Tools -> black
.Alternatively, you can set a keyboard shortcut by navigating to
Preferences or Settings -> Keymap -> External Tools -> External Tools - Black
.
As file watcher¶
Install
black
.$ pip install black
Locate your
black
installation folder.On macOS / Linux / BSD:
$ which black /usr/local/bin/black # possible location
On Windows:
$ where black %LocalAppData%\Programs\Python\Python36-32\Scripts\black.exe # possible location
Note that if you are using a virtual environment detected by PyCharm, this is an unneeded step. In this case the path to
black
is$PyInterpreterDirectory$/black
.Make sure you have the File Watchers plugin installed.
Go to
Preferences or Settings -> Tools -> File Watchers
and click+
to add a new watcher:Name: Black
File type: Python
Scope: Project Files
Program: <install_location_from_step_2>
Arguments:
$FilePath$
Output paths to refresh:
$FilePath$
Working directory:
$ProjectFileDir$
In Advanced Options
Uncheck “Auto-save edited files to trigger the watcher”
Uncheck “Trigger the watcher on external changes”
Wing IDE¶
Wing IDE supports black
via Preference Settings for system wide settings and
Project Properties for per-project or workspace specific settings, as explained in
the Wing documentation on
Auto-Reformatting. The detailed
procedure is:
Prerequistes¶
Wing IDE version 8.0+
Install
black
.$ pip install black
Make sure it runs from the command line, e.g.
$ black --help
Preference Settings¶
If you want Wing IDE to always reformat with black
for every project, follow these
steps:
In menubar navigate to
Edit -> Preferences -> Editor -> Reformatting
.Set Auto-Reformat from
disable
(default) toLine after edit
orWhole files before save
.Set Reformatter from
PEP8
(default) toBlack
.
Project Properties¶
If you want to just reformat for a specific project and not intervene with Wing IDE global setting, follow these steps:
In menubar navigate to
Project -> Project Properties -> Options
.Set Auto-Reformat from
Use Preferences setting
(default) toLine after edit
orWhole files before save
.Set Reformatter from
Use Preferences setting
(default) toBlack
.
Vim¶
Official plugin¶
Commands and shortcuts:
:Black
to format the entire file (ranges not supported);you can optionally pass
target_version=<version>
with the same values as in the command line.
:BlackUpgrade
to upgrade Black inside the virtualenv;:BlackVersion
to get the current version of Black in use.
Configuration:
g:black_fast
(defaults to0
)g:black_linelength
(defaults to88
)g:black_skip_string_normalization
(defaults to0
)g:black_skip_magic_trailing_comma
(defaults to0
)g:black_virtualenv
(defaults to~/.vim/black
or~/.local/share/nvim/black
)g:black_use_virtualenv
(defaults to1
)g:black_target_version
(defaults to""
)g:black_quiet
(defaults to0
)g:black_preview
(defaults to0
)
Installation¶
This plugin requires Vim 7.0+ built with Python 3.8+ support. It needs Python 3.8 to be able to run Black inside the Vim process which is much faster than calling an external command.
vim-plug
¶
To install with vim-plug:
Black’s stable
branch tracks official version updates, and can be used to simply
follow the most recent stable version.
Plug 'psf/black', { 'branch': 'stable' }
Another option which is a bit more explicit and offers more control is to use
vim-plug
’s tag
option with a shell wildcard. This will resolve to the latest tag
which matches the given pattern.
The following matches all stable versions (see the Release Process section for documentation of version scheme used by Black):
Plug 'psf/black', { 'tag': '*.*.*' }
and the following demonstrates pinning to a specific year’s stable style (2022 in this case):
Plug 'psf/black', { 'tag': '22.*.*' }
Vundle¶
or with Vundle:
Plugin 'psf/black'
and execute the following in a terminal:
$ cd ~/.vim/bundle/black
$ git checkout origin/stable -b stable
Arch Linux¶
On Arch Linux, the plugin is shipped with the
python-black
package, so you
can start using it in Vim after install with no additional setup.
Vim 8 Native Plugin Management¶
or you can copy the plugin files from plugin/black.vim and autoload/black.vim.
mkdir -p ~/.vim/pack/python/start/black/plugin
mkdir -p ~/.vim/pack/python/start/black/autoload
curl https://raw.githubusercontent.com/psf/black/stable/plugin/black.vim -o ~/.vim/pack/python/start/black/plugin/black.vim
curl https://raw.githubusercontent.com/psf/black/stable/autoload/black.vim -o ~/.vim/pack/python/start/black/autoload/black.vim
Let me know if this requires any changes to work with Vim 8’s builtin packadd
, or
Pathogen, and so on.
Usage¶
On first run, the plugin creates its own virtualenv using the right Python version and
automatically installs Black. You can upgrade it later by calling :BlackUpgrade
and
restarting Vim.
If you need to do anything special to make your virtualenv work and install Black (for
example you want to run a version from main), create a virtualenv manually and point
g:black_virtualenv
to it. The plugin will use it.
If you would prefer to use the system installation of Black rather than a virtualenv, then add this to your vimrc:
let g:black_use_virtualenv = 0
Note that the :BlackUpgrade
command is only usable and useful with a virtualenv, so
when the virtualenv is not in use, :BlackUpgrade
is disabled. If you need to upgrade
the system installation of Black, then use your system package manager or pip–
whatever tool you used to install Black originally.
To run Black on save, add the following lines to .vimrc
or init.vim
:
augroup black_on_save
autocmd!
autocmd BufWritePre *.py Black
augroup end
To run Black on a key press (e.g. F9 below), add this:
nnoremap <F9> :Black<CR>
With ALE¶
Install
ale
Install
black
Add this to your vimrc:
let g:ale_fixers = {} let g:ale_fixers.python = ['black']
Gedit¶
gedit is the default text editor of the GNOME, Unix like Operating Systems. Open gedit as
$ gedit <file_name>
Go to edit > preferences > plugins
Search for
external tools
and activate it.In
Tools menu -> Manage external tools
Add a new tool using
+
button.Copy the below content to the code window.
#!/bin/bash
Name=$GEDIT_CURRENT_DOCUMENT_NAME
black $Name
Set a keyboard shortcut if you like, Ex.
ctrl-B
Save:
Nothing
Input:
Nothing
Output:
Display in bottom pane
if you like.Change the name of the tool if you like.
Use your keyboard shortcut or Tools -> External Tools
to use your new tool. When you
close and reopen your File, Black will be done with its job.
Visual Studio Code¶
Use the Python extension (instructions).
Alternatively the pre-release Black Formatter extension can be used which runs a Language Server Protocol server for Black. Formatting is much more responsive using this extension, but the minimum supported version of Black is 22.3.0.
SublimeText¶
For SublimeText 3, use sublack plugin. For higher versions, it is recommended to use LSP as documented below.
Python LSP Server¶
If your editor supports the Language Server Protocol (Atom, Sublime Text, Visual Studio Code and many more), you can use the Python LSP Server with the python-lsp-black plugin.
Atom/Nuclide¶
Use python-black or formatters-python.
Gradle (the build tool)¶
Use the Spotless plugin.
Kakoune¶
Add the following hook to your kakrc, then run Black with :format
.
hook global WinSetOption filetype=python %{
set-option window formatcmd 'black -q -'
}
Thonny¶
GitHub Actions integration¶
You can use Black within a GitHub Actions workflow without setting your own Python environment. Great for enforcing that your code matches the Black code style.
Compatibility¶
This action is known to support all GitHub-hosted runner OSes. In addition, only published versions of Black are supported (i.e. whatever is available on PyPI).
Finally, this action installs Black with the colorama
extra so the --color
flag
should work fine.
Usage¶
Create a file named .github/workflows/black.yml
inside your repository with:
name: Lint
on: [push, pull_request]
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: psf/black@stable
We recommend the use of the @stable
tag, but per version tags also exist if you prefer
that. Note that the action’s version you select is independent of the version of Black
the action will use.
The version of Black the action will use can be configured via version
or read from
the pyproject.toml
file. version
can be any
valid version specifier
or just the version number if you want an exact version. To read the version from the
pyproject.toml
file instead, set use_pyproject
to true
. This will first look into
the tool.black.required-version
field, then the project.dependencies
array and
finally the project.optional-dependencies
table. The action defaults to the latest
release available on PyPI. Only versions available from PyPI are supported, so no commit
SHAs or branch names.
If you want to include Jupyter Notebooks, Black must be installed with the jupyter
extra. Installing the extra and including Jupyter Notebook files can be configured via
jupyter
(default is false
).
You can also configure the arguments passed to Black via options
(defaults to
'--check --diff'
) and src
(default is '.'
). Please note that the
--check
flag is required so that the workflow fails if Black
finds files that need to be formatted.
Here’s an example configuration:
- uses: psf/black@stable
with:
options: "--check --verbose"
src: "./src"
jupyter: true
version: "21.5b1"
If you want to match versions covered by Black’s
stability policy, you can use the compatible release operator
(~=
):
- uses: psf/black@stable
with:
options: "--check --verbose"
src: "./src"
version: "~= 22.0"
If you want to read the version from pyproject.toml
, set use_pyproject
to true
:
- uses: psf/black@stable
with:
options: "--check --verbose"
src: "./src"
use_pyproject: true
Version control integration¶
Use pre-commit. Once you
have it installed, add this to the
.pre-commit-config.yaml
in your repository:
repos:
# Using this mirror lets us use mypyc-compiled black, which is about 2x faster
- repo: https://github.com/psf/black-pre-commit-mirror
rev: 24.4.2
hooks:
- id: black
# It is recommended to specify the latest version of Python
# supported by your project here, or alternatively use
# pre-commit's default_language_version, see
# https://pre-commit.com/#top_level-default_language_version
language_version: python3.11
Feel free to switch out the rev
value to a different version of Black.
Note if you’d like to use a specific commit in rev
, you’ll need to swap the repo
specified from the mirror to https://github.com/psf/black. We discourage the use of
branches or other mutable refs since the hook won’t auto update as you may
expect.
Jupyter Notebooks¶
There is an alternate hook black-jupyter
that expands the targets of black
to
include Jupyter Notebooks. To use this hook, simply replace the hook’s id: black
with
id: black-jupyter
in the .pre-commit-config.yaml
:
repos:
# Using this mirror lets us use mypyc-compiled black, which is about 2x faster
- repo: https://github.com/psf/black-pre-commit-mirror
rev: 24.4.2
hooks:
- id: black-jupyter
# It is recommended to specify the latest version of Python
# supported by your project here, or alternatively use
# pre-commit's default_language_version, see
# https://pre-commit.com/#top_level-default_language_version
language_version: python3.11
Note
The black-jupyter
hook became available in version 21.8b0.
Black can be integrated into many environments, providing a better and smoother experience. Documentation for integrating Black with a tool can be found for the following areas:
Editors and tools not listed will require external contributions.
Patches welcome! ✨ 🍰 ✨
Any tool can pipe code through Black using its stdio mode (just
use -
as the file name).
The formatted code will be returned on stdout (unless --check
was passed). Black
will still emit messages on stderr but that shouldn’t affect your use case.
This can be used for example with PyCharm’s or IntelliJ’s File Watchers.
Guides¶
Introducing Black to your project¶
Note
This guide is incomplete. Contributions are welcomed and would be deeply appreciated!
Avoiding ruining git blame¶
A long-standing argument against moving to automated code formatters like Black is
that the migration will clutter up the output of git blame
. This was a valid argument,
but since Git version 2.23, Git natively supports
ignoring revisions in blame
with the --ignore-rev
option. You can also pass a file listing the revisions to ignore
using the --ignore-revs-file
option. The changes made by the revision will be ignored
when assigning blame. Lines modified by an ignored revision will be blamed on the
previous revision that modified those lines.
So when migrating your project’s code style to Black, reformat everything and commit
the changes (preferably in one massive commit). Then put the full 40 characters commit
identifier(s) into a file usually called .git-blame-ignore-revs
at the root of your
project directory.
# Migrate code style to Black
5b4ab991dede475d393e9d69ec388fd6bd949699
Afterwards, you can pass that file to git blame
and see clean and meaningful blame
information.
$ git blame important.py --ignore-revs-file .git-blame-ignore-revs
7a1ae265 (John Smith 2019-04-15 15:55:13 -0400 1) def very_important_function(text, file):
abdfd8b0 (Alice Doe 2019-09-23 11:39:32 -0400 2) text = text.lstrip()
7a1ae265 (John Smith 2019-04-15 15:55:13 -0400 3) with open(file, "r+") as f:
7a1ae265 (John Smith 2019-04-15 15:55:13 -0400 4) f.write(formatted)
You can even configure git
to automatically ignore revisions listed in a file on every
call to git blame
.
$ git config blame.ignoreRevsFile .git-blame-ignore-revs
The one caveat is that some online Git-repositories like GitLab do not yet support
ignoring revisions using their native blame UI. So blame information will be cluttered
with a reformatting commit on those platforms. (If you’d like this feature, there’s an
open issue for GitLab).
GitHub supports .git-blame-ignore-revs
by default in blame views however.
Using Black with other tools¶
Black compatible configurations¶
All of Black’s changes are harmless (or at least, they should be), but a few do conflict against other tools. It is not uncommon to be using other tools alongside Black like linters and type checkers. Some of them need a bit of tweaking to resolve the conflicts. Listed below are Black compatible configurations in various formats for the common tools out there.
Please note that Black only supports the TOML file format for its configuration
(e.g. pyproject.toml
). The provided examples are to only configure their corresponding
tools, using their supported file formats.
Compatible configuration files can be found here.
isort¶
isort helps to sort and format imports in your Python code. Black also formats imports, but in a different way from isort’s defaults which leads to conflicting changes.
Profile¶
Since version 5.0.0, isort supports
profiles to allow easy
interoperability with common code styles. You can set the black profile in any of the
config files
supported by isort. Below, an example for pyproject.toml
:
[tool.isort]
profile = "black"
Custom Configuration¶
If you’re using an isort version that is older than 5.0.0 or you have some custom
configuration for Black, you can tweak your isort configuration to make it compatible
with Black. Below, an example for .isort.cfg
:
multi_line_output = 3
include_trailing_comma = True
force_grid_wrap = 0
use_parentheses = True
ensure_newline_before_comments = True
line_length = 88
Why those options above?¶
Black wraps imports that surpass line-length
by moving identifiers onto separate
lines and by adding a trailing comma after each. A more detailed explanation of this
behaviour can be
found here.
isort’s default mode of wrapping imports that extend past the line_length
limit is
“Grid”.
from third_party import (lib1, lib2, lib3,
lib4, lib5, ...)
This style is incompatible with Black, but isort can be configured to use a different wrapping mode called “Vertical Hanging Indent” which looks like this:
from third_party import (
lib1,
lib2,
lib3,
lib4,
)
This style is Black compatible and can be achieved by multi-line-output = 3
. Also,
as mentioned above, when wrapping long imports Black puts a trailing comma and uses
parentheses. isort should follow the same behaviour and passing the options
include_trailing_comma = True
and use_parentheses = True
configures that.
The option force_grid_wrap = 0
is just to tell isort to only wrap imports that surpass
the line_length
limit.
Finally, isort should be told to wrap imports when they surpass Black’s default limit
of 88 characters via line_length = 88
as well as
ensure_newline_before_comments = True
to ensure spacing import sections with comments
works the same as with Black.
Please note ensure_newline_before_comments = True
only works since isort >= 5 but
does not break older versions so you can keep it if you are running previous versions.
Formats¶
.isort.cfg
[settings]
profile = black
setup.cfg
[isort]
profile = black
pyproject.toml
[tool.isort]
profile = 'black'
.editorconfig
[*.py]
profile = black
pycodestyle¶
pycodestyle is a code linter. It warns you of syntax errors, possible bugs, stylistic errors, etc. For the most part, pycodestyle follows PEP 8 when warning about stylistic errors. There are a few deviations that cause incompatibilities with Black.
Configuration¶
max-line-length = 88
ignore = E203,E701
Why those options above?¶
max-line-length
¶
As with isort, pycodestyle should be configured to allow lines up to the length limit of
88
, Black’s default.
E203
¶
In some cases, as determined by PEP 8, Black will enforce an equal amount of
whitespace around slice operators. Due to this, pycodestyle will raise
E203 whitespace before ':'
warnings. Since this warning is not PEP 8 compliant, it
should be disabled.
E701
/ E704
¶
Black will collapse implementations of classes and functions consisting solely of ..
to a single line. This matches how such examples are formatted in PEP 8. It remains true
that in all other cases Black will prevent multiple statements on the same line, in
accordance with PEP 8 generally discouraging this.
However, pycodestyle
does not mirror this logic and may raise
E701 multiple statements on one line (colon)
in this situation. Its
disabled-by-default E704 multiple statements on one line (def)
rule may also raise
warnings and should not be enabled.
W503
¶
When breaking a line, Black will break it before a binary operator. This is compliant
with PEP 8 as of
April 2016.
There’s a disabled-by-default warning in Flake8 which goes against this PEP 8
recommendation called W503 line break before binary operator
. It should not be enabled
in your configuration. You can use its counterpart
W504 line break after binary operator
instead.
Formats¶
setup.cfg, .pycodestyle, tox.ini
[pycodestyle]
max-line-length = 88
ignore = E203,E701
Flake8¶
Flake8 is a wrapper around multiple linters, including pycodestyle. As such, it has many of the same issues.
Bugbear¶
It’s recommended to use the Bugbear plugin and enable its B950 check instead of using Flake8’s E501, because it aligns with Black’s 10% rule.
Install Bugbear and use the following config:
[flake8]
max-line-length = 80
extend-select = B950
extend-ignore = E203,E501,E701
Minimal Configuration¶
In cases where you can’t or don’t want to install Bugbear, you can use this minimally compatible config:
[flake8]
max-line-length = 88
extend-ignore = E203,E701
Why those options above?¶
See the pycodestyle section above.
Formats¶
.flake8, setup.cfg, tox.ini
[flake8]
max-line-length = 88
extend-ignore = E203,E701
Pylint¶
Pylint is also a code linter like Flake8. It has many of the same checks as Flake8 and more. It particularly has more formatting checks regarding style conventions like variable naming.
Configuration¶
max-line-length = 88
Why those options above?¶
Pylint should be configured to only complain about lines that surpass 88
characters
via max-line-length = 88
.
If using pylint<2.6.0
, also disable C0326
and C0330
as these are incompatible with
Black formatting and have since been removed.
Formats¶
pylintrc
[format]
max-line-length = 88
setup.cfg
[pylint]
max-line-length = 88
pyproject.toml
[tool.pylint.format]
max-line-length = "88"
Wondering how to do something specific? You’ve found the right place! Listed below are topic specific guides available:
Frequently Asked Questions¶
The most common questions and issues users face are aggregated to this FAQ.
Why spaces? I prefer tabs¶
PEP 8 recommends spaces over tabs, and they are used by most of the Python community. Black provides no options to configure the indentation style, and requests for such options will not be considered.
However, we recognise that using tabs is an accessibility issue as well. While the
option will never be added to Black, visually impaired developers may find conversion
tools such as expand/unexpand
(for Linux) useful when contributing to Python projects.
A workflow might consist of e.g. setting up appropriate pre-commit and post-merge git
hooks, and scripting unexpand
to run after applying Black.
Does Black have an API?¶
Not yet. Black is fundamentally a command line tool. Many integrations are provided, but a Python interface is not one of them. A simple API is being planned though.
Is Black safe to use?¶
Yes. Black is strictly about formatting, nothing else. Black strives to ensure that
after formatting the AST is
checked with
limited special cases where the code is allowed to differ. If issues are found, an error
is raised and the file is left untouched. Magical comments that influence linters and
other tools, such as # noqa
, may be moved by Black. See below for more details.
How stable is Black’s style?¶
Stable. Black aims to enforce one style and one style only, with some room for pragmatism. See The Black Code Style for more details.
Starting in 2022, the formatting output is stable for the releases made in the same year
(other than unintentional bugs). At the beginning of every year, the first release will
make changes to the stable style. It is possible to opt in to the latest formatting
styles using the --preview
flag.
Why is my file not formatted?¶
Most likely because it is ignored in .gitignore
or excluded with configuration. See
file collection and discovery
for details.
Why is my Jupyter Notebook cell not formatted?¶
Black is timid about formatting Jupyter Notebooks. Cells containing any of the following will not be formatted:
automagics (e.g.
pip install black
)non-Python cell magics (e.g.
%%writefile
). These can be added with the flag--python-cell-magics
, e.g.black --python-cell-magics writefile hello.ipynb
.multiline magics, e.g.:
%timeit f(1, \ 2, \ 3)
code which
IPython
’sTransformerManager
would transform magics into, e.g.:get_ipython().system('ls')
invalid syntax, as it can’t be safely distinguished from automagics in the absence of a running
IPython
kernel.
Why does Flake8 report warnings?¶
Some of Flake8’s rules conflict with Black’s style. We recommend disabling these rules. See Using Black with other tools.
Which Python versions does Black support?¶
Currently the runtime requires Python 3.8-3.11. Formatting is supported for files containing syntax from Python 3.3 to 3.11. We promise to support at least all Python versions that have not reached their end of life. This is the case for both running Black and formatting code.
Support for formatting Python 2 code was removed in version 22.0. While we’ve made no plans to stop supporting older Python 3 minor versions immediately, their support might also be removed some time in the future without a deprecation period.
Runtime support for 3.7 was removed in version 23.7.0.
Why does my linter or typechecker complain after I format my code?¶
Some linters and other tools use magical comments (e.g., # noqa
, # type: ignore
) to
influence their behavior. While Black does its best to recognize such comments and leave
them in the right place, this detection is not and cannot be perfect. Therefore, you’ll
sometimes have to manually move these comments to the right place after you format your
codebase with Black.
Can I run Black with PyPy?¶
Yes, there is support for PyPy 3.8 and higher.
Why does Black not detect syntax errors in my code?¶
Black is an autoformatter, not a Python linter or interpreter. Detecting all syntax errors is not a goal. It can format all code accepted by CPython (if you find an example where that doesn’t hold, please report a bug!), but it may also format some code that CPython doesn’t accept.
What is compiled: yes/no
all about in the version output?¶
While Black is indeed a pure Python project, we use mypyc to compile Black into a C Python extension, usually doubling performance. These compiled wheels are available for 64-bit versions of Windows, Linux (via the manylinux standard), and macOS across all supported CPython versions.
Platforms including musl-based and/or ARM Linux distributions, and ARM Windows are currently not supported. These platforms will fall back to the slower pure Python wheel available on PyPI.
If you are experiencing exceptionally weird issues or even segfaults, you can try
passing --no-binary black
to your pip install invocation. This flag excludes all
wheels (including the pure Python wheel), so this command will use the sdist.
Contributing¶
The basics¶
An overview on contributing to the Black project.
Technicalities¶
Development on the latest version of Python is preferred. You can use any operating system.
Install development dependencies inside a virtual environment of your choice, for example:
$ python3 -m venv .venv
$ source .venv/bin/activate # activation for linux and mac
$ .venv\Scripts\activate # activation for windows
(.venv)$ pip install -r test_requirements.txt
(.venv)$ pip install -e .[d]
(.venv)$ pre-commit install
Before submitting pull requests, run lints and tests with the following commands from the root of the black repo:
# Linting
(.venv)$ pre-commit run -a
# Unit tests
(.venv)$ tox -e py
# Optional Fuzz testing
(.venv)$ tox -e fuzz
# Format Black itself
(.venv)$ tox -e run_self
Development¶
Further examples of invoking the tests
# Run all of the above mentioned, in parallel
(.venv)$ tox --parallel=auto
# Run tests on a specific python version
(.venv)$ tox -e py39
# pass arguments to pytest
(.venv)$ tox -e py -- --no-cov
# print full tree diff, see documentation below
(.venv)$ tox -e py -- --print-full-tree
# disable diff printing, see documentation below
(.venv)$ tox -e py -- --print-tree-diff=False
Testing¶
All aspects of the Black style should be tested. Normally, tests should be created as
files in the tests/data/cases
directory. These files consist of up to three parts:
A line that starts with
# flags:
followed by a set of command-line options. For example, if the line is# flags: --preview --skip-magic-trailing-comma
, the test case will be run with preview mode on and the magic trailing comma off. The options accepted are mostly a subset of those of Black itself, except for the--minimum-version=
flag, which should be used when testing a grammar feature that works only in newer versions of Python. This flag ensures that we don’t try to validate the AST on older versions and tests that we autodetect the Python version correctly when the feature is used. For the exact flags accepted, see the functionget_flags_parser
intests/util.py
. If this line is omitted, the default options are used.A block of Python code used as input for the formatter.
The line
# output
, followed by the output of Black when run on the previous block. If this is omitted, the test asserts that Black will leave the input code unchanged.
Black has two pytest command-line options affecting test files in tests/data/
that
are split into an input part, and an output part, separated by a line with# output
.
These can be passed to pytest
through tox
, or directly into pytest if not using
tox
.
--print-full-tree
¶
Upon a failing test, print the full concrete syntax tree (CST) as it is after processing
the input (“actual”), and the tree that’s yielded after parsing the output (“expected”).
Note that a test can fail with different output with the same CST. This used to be the
default, but now defaults to False
.
--print-tree-diff
¶
Upon a failing test, print the diff of the trees as described above. This is the
default. To turn it off pass --print-tree-diff=False
.
News / Changelog Requirement¶
Black
has CI that will check for an entry corresponding to your PR in CHANGES.md
. If
you feel this PR does not require a changelog entry please state that in a comment and a
maintainer can add a skip news
label to make the CI pass. Otherwise, please ensure you
have a line in the following format:
- `Black` is now more awesome (#X)
Note that X should be your PR number, not issue number! To workout X, please use
Next PR Number. This
is not perfect but saves a lot of release overhead as now the releaser does not need to
go back and workout what to add to the CHANGES.md
for each release.
Style Changes¶
If a change would affect the advertised code style, please modify the documentation (The
Black code style) to reflect that change. Patches that fix unintended bugs in
formatting don’t need to be mentioned separately though. If the change is implemented
with the --preview
flag, please include the change in the future style document
instead and write the changelog entry under a dedicated “Preview changes” heading.
Docs Testing¶
If you make changes to docs, you can test they still build locally too.
(.venv)$ pip install -r docs/requirements.txt
(.venv)$ pip install -e .[d]
(.venv)$ sphinx-build -a -b html -W docs/ docs/_build/
Hygiene¶
If you’re fixing a bug, add a test. Run it first to confirm it fails, then fix the bug, run it again to confirm it’s really fixed.
If adding a new feature, add a test. In fact, always add a test. But wait, before adding any large feature, first open an issue for us to discuss the idea first.
Finally¶
Thanks again for your interest in improving the project! You’re taking action when most people decide to sit and watch.
Gauging changes¶
A lot of the time, your change will affect formatting and/or performance. Quantifying these changes is hard, so we have tooling to help make it easier.
It’s recommended you evaluate the quantifiable changes your Black formatting modification causes before submitting a PR. Think about if the change seems disruptive enough to cause frustration to projects that are already “black formatted”.
diff-shades¶
diff-shades is a tool that runs Black across a list of open-source projects recording the results. The main highlight feature of diff-shades is being able to compare two revisions of Black. This is incredibly useful as it allows us to see what exact changes will occur, say merging a certain PR.
For more information, please see the diff-shades documentation.
CI integration¶
diff-shades is also the tool behind the “diff-shades results comparing …” / “diff-shades reports zero changes …” comments on PRs. The project has a GitHub Actions workflow that analyzes and compares two revisions of Black according to these rules:
Baseline revision |
Target revision |
|
---|---|---|
On PRs |
latest commit on |
PR commit with |
On pushes (main only) |
latest PyPI version |
the pushed commit |
For pushes to main, there’s only one analysis job named preview-changes
where the
preview style is used for all projects.
For PRs they get one more analysis job: assert-no-changes
. It’s similar to
preview-changes
but runs with the stable code style. It will fail if changes were
made. This makes sure code won’t be reformatted again and again within the same year in
accordance to Black’s stability policy.
Additionally for PRs, a PR comment will be posted embedding a summary of the preview changes and links to further information. If there’s a pre-existing diff-shades comment, it’ll be updated instead the next time the workflow is triggered on the same PR.
Note
The preview-changes
job will only fail intentionally if while analyzing a file failed to
format. Otherwise a failure indicates a bug in the workflow.
The workflow uploads several artifacts upon completion:
The raw analyses (.json)
HTML diffs (.html)
.pr-comment.json
(if triggered by a PR)
The last one is downloaded by the diff-shades-comment
workflow and shouldn’t be
downloaded locally. The HTML diffs come in handy for push-based where there’s no PR to
post a comment. And the analyses exist just in case you want to do further analysis
using the collected data locally.
Issue triage¶
Currently, Black uses the issue tracker for bugs, feature requests, proposed style modifications, and general user support. Each of these issues have to be triaged so they can be eventually be resolved somehow. This document outlines the triaging process and also the current guidelines and recommendations.
Tip
If you’re looking for a way to contribute without submitting patches, this might be the area for you. Since Black is a popular project, its issue tracker is quite busy and always needs more attention than is available. While triage isn’t the most glamorous or technically challenging form of contribution, it’s still important. For example, we would love to know whether that old bug report is still reproducible!
You can get easily started by reading over this document and then responding to issues.
If you contribute enough and have stayed for a long enough time, you may even be given Triage permissions!
The basics¶
Black gets a whole bunch of different issues, they range from bug reports to user support issues. To triage is to identify, organize, and kickstart the issue’s journey through its lifecycle to resolution.
More specifically, to triage an issue means to:
identify what type and categories the issue falls under
confirm bugs
ask questions / for further information if necessary
link related issues
provide the first initial feedback / support
Note that triage is typically the first response to an issue, so don’t fret if the issue doesn’t make much progress after initial triage. The main goal of triaging to prepare the issue for future more specific development or discussion, so eventually it will be resolved.
The lifecycle of a bug report or user support issue typically goes something like this:
the issue is waiting for triage
identified - has been marked with a type label and other relevant labels, more details or a functional reproduction may be still needed (and therefore should be marked with
S: needs repro
orS: awaiting response
)confirmed - the issue can reproduced and necessary details have been provided
discussion - initial triage has been done and now the general details on how the issue should be best resolved are being hashed out
awaiting fix - no further discussion on the issue is necessary and a resolving PR is the next step
closed - the issue has been resolved, reasons include:
the issue couldn’t be reproduced
the issue has been fixed
duplicate of another pre-existing issue or is invalid
For enhancement, documentation, and style issues, the lifecycle looks very similar but the details are different:
the issue is waiting for triage
identified - has been marked with a type label and other relevant labels
discussion - the merits of the suggested changes are currently being discussed, a PR would be acceptable but would be at significant risk of being rejected
accepted & awaiting PR - it’s been determined the suggested changes are OK and a PR would be welcomed (
S: accepted
)closed: - the issue has been resolved, reasons include:
the suggested changes were implemented
it was rejected (due to technical concerns, ethos conflicts, etc.)
duplicate of a pre-existing issue or is invalid
Note: documentation issues don’t use the S: accepted
label currently since they’re
less likely to be rejected.
Labelling¶
We use labels to organize, track progress, and help effectively divvy up work.
Our labels are divided up into several groups identified by their prefix:
T - Type: the general flavor of issue / PR
C - Category: areas of concerns, ranges from bug types to project maintenance
F - Formatting Area: like C but for formatting specifically
S - Status: what stage of resolution is this issue currently in?
R - Resolution: how / why was the issue / PR resolved?
We also have a few standalone labels:
good first issue
: issues that are beginner-friendly (and will show up in GitHub banners for first-time visitors to the repository)help wanted
: complex issues that need and are looking for a fair bit of work as to progress (will also show up in various GitHub pages)skip news
: for PRs that are trivial and don’t need a CHANGELOG entry (and skips the CHANGELOG entry check)
Note
We do use labels for PRs, in particular the skip news
label, but we aren’t that
rigorous about it. Just follow your judgement on what labels make sense for the
specific PR (if any even make sense).
Projects¶
For more general and broad goals we use projects to track work. Some may be longterm projects with no true end (e.g. the “Amazing documentation” project) while others may be more focused and have a definite end (like the “Getting to beta” project).
Note
To modify GitHub Projects you need the Write repository permission level or higher.
Closing issues¶
Closing an issue signifies the issue has reached the end of its life, so closing issues should be taken with care. The following is the general recommendation for each type of issue. Note that these are only guidelines and if your judgement says something else it’s totally cool to go with it instead.
For most issues, closing the issue manually or automatically after a resolving PR is
ideal. For bug reports specifically, if the bug has already been fixed, try to check in
with the issue opener that their specific case has been resolved before closing. Note
that we close issues as soon as they’re fixed in the main
branch. This doesn’t
necessarily mean they’ve been released yet.
Design and enhancement issues should be also closed when it’s clear the proposed change won’t be implemented, whether that has been determined after a lot of discussion or just simply goes against Black’s ethos. If such an issue turns heated, closing and locking is acceptable if it’s severe enough (although checking in with the core team is probably a good idea).
User support issues are best closed by the author or when it’s clear the issue has been resolved in some sort of manner.
Duplicates and invalid issues should always be closed since they serve no purpose and add noise to an already busy issue tracker. Although be careful to make sure it’s truly a duplicate and not just very similar before labelling and closing an issue as duplicate.
Common reports¶
Some issues are frequently opened, like issues about Black formatted code causing E203 messages. Even though these issues are probably heavily duplicated, they still require triage sucking up valuable time from other things (although they usually skip most of their lifecycle since they’re closed on triage).
Here’s some of the most common issues and also pre-made responses you can use:
“The trailing comma isn’t being removed by Black!”¶
Black used to remove the trailing comma if the expression fits in a single line, but this was changed by #826 and #1288. Now a trailing comma tells Black to always explode the expression. This change was made mostly for the cases where you _know_ a collection or whatever will grow in the future. Having it always exploded as one element per line reduces diff noise when adding elements. Before the "magic trailing comma" feature, you couldn't anticipate a collection's growth reliably since collections that fitted in one line were ruthlessly collapsed regardless of your intentions. One of Black's goals is reducing diff noise, so this was a good pragmatic change.
So no, this is not a bug, but an intended feature. Anyway, [here's the documentation](https://github.com/psf/black/blob/master/docs/the_black_code_style.md#the-magic-trailing-comma) on the "magic trailing comma", including the ability to skip this functionality with the `--skip-magic-trailing-comma` option. Hopefully that helps solve the possible confusion.
“Black formatted code is violating Flake8’s E203!”¶
Hi,
This is expected behaviour, please see the documentation regarding this case (emphasis
mine):
> PEP 8 recommends to treat : in slices as a binary operator with the lowest priority, and to leave an equal amount of space on either side, **except if a parameter is omitted (e.g. ham[1 + 1 :])**. It recommends no spaces around : operators for “simple expressions” (ham[lower:upper]), and **extra space for “complex expressions” (ham[lower : upper + offset])**. **Black treats anything more than variable names as “complex” (ham[lower : upper + 1]).** It also states that for extended slices, both : operators have to have the same amount of spacing, except if a parameter is omitted (ham[1 + 1 ::]). Black enforces these rules consistently.
> This behaviour may raise E203 whitespace before ':' warnings in style guide enforcement tools like Flake8. **Since E203 is not PEP 8 compliant, you should tell Flake8 to ignore these warnings**.
https://black.readthedocs.io/en/stable/the_black_code_style/current_style.html#slices
Have a good day!
Release process¶
Black has had a lot of work done into standardizing and automating its release process. This document sets out to explain how everything works and how to release Black using said automation.
Release cadence¶
We aim to release whatever is on main
every 1-2 months. This ensures merged
improvements and bugfixes are shipped to users reasonably quickly, while not massively
fracturing the user-base with too many versions. This also keeps the workload on
maintainers consistent and predictable.
If there’s not much new on main
to justify a release, it’s acceptable to skip a
month’s release. Ideally January releases should not be skipped because as per our
stability policy, the first release in a new calendar year
may make changes to the stable style. While the policy applies to the first release
(instead of only January releases), confining changes to the stable style to January
will keep things predictable (and nicer) for users.
Unless there is a serious regression or bug that requires immediate patching, there should not be more than one release per month. While version numbers are cheap, releases require a maintainer to both commit to do the actual cutting of a release, but also to be able to deal with the potential fallout post-release. Releasing more frequently than monthly nets rapidly diminishing returns.
Cutting a release¶
You must have write
permissions for the Black repository to cut a release.
The 10,000 foot view of the release process is that you prepare a release PR and then publish a GitHub Release. This triggers release automation that builds all release artifacts and publishes them to the various platforms we publish to.
We now have a scripts/release.py
script to help with cutting the release PRs.
python3 scripts/release.py --help
is your friend.release.py
has only been tested in Python 3.12 (so get with the times :D)
To cut a release:
Determine the release’s version number
Black follows the CalVer versioning standard using the
YY.M.N
formatSo unless there already has been a release during this month,
N
should be0
Example: the first release in January, 2022 →
22.1.0
release.py
will calculate this and log to stderr for you copy paste pleasure
File a PR editing
CHANGES.md
and the docs to version the latest changesRun
python3 scripts/release.py [--debug]
to generate most changesSub headings in the template, if they have no bullet points need manual removal PR welcome to improve :D
If
release.py
fail manually edit; otherwise, yay, skip this step!Replace the
## Unreleased
header with the version numberRemove any empty sections for the current release
(optional) Read through and copy-edit the changelog (eg. by moving entries, fixing typos, or rephrasing entries)
Double-check that no changelog entries since the last release were put in the wrong section (e.g., run
git diff <last release> CHANGES.md
)Update references to the latest version in Version control integration and The basics
Example PR: GH-3139
Once the release PR is merged, wait until all CI passes
If CI does not pass, stop and investigate the failure(s) as generally we’d want to fix failing CI before cutting a release
-
Click
Choose a tag
and type in the version number, then select theCreate new tag: YY.M.N on publish
option that appearsVerify that the new tag targets the
main
branchYou can leave the release title blank, GitHub will default to the tag name
Copy and paste the raw changelog Markdown for the current release into the description box
Publish the GitHub Release, triggering release automation that will handle the rest
Once CI is done add + commit (git push - No review) a new empty template for the next release to CHANGES.md (Template is able to be copy pasted from release.py should we fail)
python3 scripts/release.py --add-changes-template|-a [--debug]
Should that fail, please return to copy + paste
At this point, you’re basically done. It’s good practice to go and watch and verify that all the release workflows pass, although you will receive a GitHub notification should something fail.
If something fails, don’t panic. Please go read the respective workflow’s logs and configuration file to reverse-engineer your way to a fix/solution.
Congratulations! You’ve successfully cut a new release of Black. Go and stand up and take a break, you deserve it.
Important
Once the release artifacts reach PyPI, you may see new issues being filed indicating regressions. While regressions are not great, they don’t automatically mean a hotfix release is warranted. Unless the regressions are serious and impact many users, a hotfix release is probably unnecessary.
In the end, use your best judgement and ask other maintainers for their thoughts.
Release workflows¶
All of Black’s release automation uses GitHub Actions. All workflows are therefore
configured using YAML files in the .github/workflows
directory of the Black
repository.
They are triggered by the publication of a GitHub Release.
Below are descriptions of our release workflows.
Publish to PyPI¶
This is our main workflow. It builds an sdist and wheels to upload to PyPI where the vast majority of users will download Black from. It’s divided into three job groups:
sdist + pure wheel¶
This single job builds the sdist and pure Python wheel (i.e., a wheel that only contains Python code) using build and then uploads them to PyPI using twine. These artifacts are general-purpose and can be used on basically any platform supported by Python.
mypyc wheels (…)¶
We use mypyc to compile Black into a CPython C extension for significantly improved performance. Wheels built with mypyc are platform and Python version specific. Supported platforms are documented in the FAQ.
These matrix jobs use cibuildwheel which handles the complicated task of building C extensions for many environments for us. Since building these wheels is slow, there are multiple mypyc wheels jobs (hence the term “matrix”) that build for a specific platform (as noted in the job name in parentheses).
Like the previous job group, the built wheels are uploaded to PyPI using twine.
Update stable branch¶
So this job doesn’t really belong here, but updating the stable
branch after the
other PyPI jobs pass (they must pass for this job to start) makes the most sense. This
saves us from remembering to update the branch sometime after cutting the release.
Currently this workflow uses an API token associated with @ambv’s PyPI account
Publish executables¶
This workflow builds native executables for multiple platforms using PyInstaller. This allows people to download the executable for their platform and run Black without a Python runtime installed.
The created binaries are stored on the associated GitHub Release for download over IPv4 only (GitHub still does not have IPv6 access 😢).
docker¶
This workflow uses the QEMU powered buildx
feature of Docker to upload an arm64
and
amd64
/x86_64
build of the official Black Docker image™.
Currently this workflow uses an API Token associated with @cooperlees account
Note
This also runs on each push to main
.
Welcome! Happy to see you willing to make the project better. Have you read the entire user documentation yet?
Bird’s eye view
In terms of inspiration, Black is about as configurable as gofmt (which is to say, not very). This is deliberate. Black aims to provide a consistent style and take away opportunities for arguing about style.
Bug reports and fixes are always welcome! Please follow the issue templates on GitHub for best results.
Before you suggest a new feature or configuration knob, ask yourself why you want it. If it enables better integration with some workflow, fixes an inconsistency, speeds things up, and so on - go for it! On the other hand, if your answer is “because I don’t like a particular formatting” then you’re not ready to embrace Black yet. Such changes are unlikely to get accepted. You can still try but prepare to be disappointed.
Contents
This section covers the following topics:
For an overview on contributing to the Black, please checkout The basics.
Change Log¶
Unreleased¶
Highlights¶
Stable style¶
Preview style¶
Configuration¶
Packaging¶
Packaging metadata updated: docs are explictly linked, the issue tracker is now also linked. This improves the PyPI listing for Black. (#4345)
Parser¶
Fix regression where Black failed to parse a multiline f-string containing another multiline string (#4339)
Performance¶
Output¶
Blackd¶
Integrations¶
Documentation¶
24.4.2¶
This is a bugfix release to fix two regressions in the new f-string parser introduced in 24.4.1.
Parser¶
Fix regression where certain complex f-strings failed to parse (#4332)
Performance¶
Fix bad performance on certain complex string literals (#4331)
24.4.1¶
Highlights¶
Add support for the new Python 3.12 f-string syntax introduced by PEP 701 (#3822)
Stable style¶
Fix crash involving indented dummy functions containing newlines (#4318)
Parser¶
Add support for type parameter defaults, a new syntactic feature added to Python 3.13 by PEP 696 (#4327)
Integrations¶
Github Action now works even when
git archive
is skipped (#4313)
24.4.0¶
Stable style¶
Fix unwanted crashes caused by AST equivalency check (#4290)
Preview style¶
Integrations¶
Add a new option
use_pyproject
to the GitHub Actionpsf/black
. This will read the Black version frompyproject.toml
. (#4294)
24.3.0¶
Highlights¶
This release is a milestone: it fixes Black’s first CVE security vulnerability. If you run Black on untrusted input, or if you habitually put thousands of leading tab characters in your docstrings, you are strongly encouraged to upgrade immediately to fix CVE-2024-21503.
This release also fixes a bug in Black’s AST safety check that allowed Black to make incorrect changes to certain f-strings that are valid in Python 3.12 and higher.
Stable style¶
Don’t move comments along with delimiters, which could cause crashes (#4248)
Strengthen AST safety check to catch more unsafe changes to strings. Previous versions of Black would incorrectly format the contents of certain unusual f-strings containing nested strings with the same quote type. Now, Black will crash on such strings until support for the new f-string syntax is implemented. (#4270)
Fix a bug where line-ranges exceeding the last code line would not work as expected (#4273)
Performance¶
Fix catastrophic performance on docstrings that contain large numbers of leading tab characters. This fixes CVE-2024-21503. (#4278)
Documentation¶
Note what happens when
--check
is used with--quiet
(#4236)
24.2.0¶
Stable style¶
Fixed a bug where comments where mistakenly removed along with redundant parentheses (#4218)
Preview style¶
Move the
hug_parens_with_braces_and_square_brackets
feature to the unstable style due to an outstanding crash and proposed formatting tweaks (#4198)Fixed a bug where base expressions caused inconsistent formatting of ** in tenary expression (#4154)
Checking for newline before adding one on docstring that is almost at the line limit (#4185)
Remove redundant parentheses in
case
statementif
guards (#4214).
Configuration¶
Fix issue where Black would ignore input files in the presence of symlinks (#4222)
Black now ignores
pyproject.toml
that is missing atool.black
section when discovering project root and configuration. Since Black continues to use version control as an indicator of project root, this is expected to primarily change behavior for users in a monorepo setup (desirably). If you wish to preserve previous behavior, simply add an empty[tool.black]
to the previously discoveredpyproject.toml
(#4204)
Output¶
Black will swallow any
SyntaxWarning
s orDeprecationWarning
s produced by theast
module when performing equivalence checks (#4189)
Integrations¶
Add a JSONSchema and provide a validate-pyproject entry-point (#4181)
24.1.1¶
Bugfix release to fix a bug that made Black unusable on certain file systems with strict limits on path length.
Preview style¶
Consistently add trailing comma on typed parameters (#4164)
Configuration¶
Shorten the length of the name of the cache file to fix crashes on file systems that do not support long paths (#4176)
24.1.0¶
Highlights¶
This release introduces the new 2024 stable style (#4106), stabilizing the following changes:
Add parentheses around
if
-else
expressions (#2278)Dummy class and function implementations consisting only of
...
are formatted more compactly (#3796)If an assignment statement is too long, we now prefer splitting on the right-hand side (#3368)
Hex codes in Unicode escape sequences are now standardized to lowercase (#2916)
Allow empty first lines at the beginning of most blocks (#3967, #4061)
Add parentheses around long type annotations (#3899)
Fix incorrect magic trailing comma handling in return types (#3916)
Remove blank lines before class docstrings (#3692)
Wrap multiple context managers in parentheses if combined in a single
with
statement (#3489)Fix bug in line length calculations for power operations (#3942)
Add trailing commas to collection literals even if there’s a comment after the last entry (#3393)
When using
--skip-magic-trailing-comma
or-C
, trailing commas are stripped from subscript expressions with more than 1 element (#3209)Add extra blank lines in stubs in a few cases (#3564, #3862)
Accept raw strings as docstrings (#3947)
Split long lines in case blocks (#4024)
Stop removing spaces from walrus operators within subscripts (#3823)
Fix incorrect formatting of certain async statements (#3609)
Allow combining
# fmt: skip
with other comments (#3959)
There are already a few improvements in the --preview
style, which are slated for the
2025 stable style. Try them out and
share your feedback. In the past, the preview
style has included some features that we were not able to stabilize. This year, we’re
adding a separate --unstable
style for features with known problems. Now, the
--preview
style only includes features that we actually expect to make it into next
year’s stable style.
Stable style¶
Several bug fixes were made in features that are moved to the stable style in this release:
Fix comment handling when parenthesising conditional expressions (#4134)
Fix bug where spaces were not added around parenthesized walruses in subscripts, unlike other binary operators (#4109)
Remove empty lines before docstrings in async functions (#4132)
Address a missing case in the change to allow empty lines at the beginning of all blocks, except immediately before a docstring (#4130)
For stubs, fix logic to enforce empty line after nested classes with bodies (#4141)
Preview style¶
Add
--unstable
style, covering preview features that have known problems that would block them from going into the stable style. Also add the--enable-unstable-feature
flag; for example, use--enable-unstable-feature hug_parens_with_braces_and_square_brackets
to apply this preview feature throughout 2024, even if a later Black release downgrades the feature to unstable (#4096)Format module docstrings the same as class and function docstrings (#4095)
Fix crash when using a walrus in a dictionary (#4155)
Fix unnecessary parentheses when wrapping long dicts (#4135)
Stop normalizing spaces before
# fmt: skip
comments (#4146)
Configuration¶
Print warning when configuration in
pyproject.toml
contains an invalid key (#4165)Fix symlink handling, properly ignoring symlinks that point outside of root (#4161)
Fix cache mtime logic that resulted in false positive cache hits (#4128)
Remove the long-deprecated
--experimental-string-processing
flag. This feature can currently be enabled with--preview --enable-unstable-feature string_processing
. (#4096)
Integrations¶
23.12.1¶
Packaging¶
Fixed a bug that included dependencies from the
d
extra by default (#4108)
23.12.0¶
Highlights¶
It’s almost 2024, which means it’s time for a new edition of Black’s stable style! Together with this release, we’ll put out an alpha release 24.1a1 showcasing the draft 2024 stable style, which we’ll finalize in the January release. Please try it out and share your feedback.
This release (23.12.0) will still produce the 2023 style. Most but not all of the
changes in --preview
mode will be in the 2024 stable style.
Stable style¶
Preview style¶
Prefer more equal signs before a break when splitting chained assignments (#4010)
Standalone form feed characters at the module level are no longer removed (#4021)
Additional cases of immediately nested tuples, lists, and dictionaries are now indented less (#4012)
Allow empty lines at the beginning of all blocks, except immediately before a docstring (#4060)
Fix crash in preview mode when using a short
--line-length
(#4086)Keep suites consisting of only an ellipsis on their own lines if they are not functions or class definitions (#4066) (#4103)
Configuration¶
--line-ranges
now skips Black’s internal stability check in--safe
mode. This avoids a crash on rare inputs that have many unformatted same-content lines. (#4034)
Packaging¶
Integrations¶
23.11.0¶
Highlights¶
Support formatting ranges of lines with the new
--line-ranges
command-line option (#4020)
Stable style¶
Fix crash on formatting bytes strings that look like docstrings (#4003)
Fix crash when whitespace followed a backslash before newline in a docstring (#4008)
Fix standalone comments inside complex blocks crashing Black (#4016)
Fix crash on formatting code like
await (a ** b)
(#3994)No longer treat leading f-strings as docstrings. This matches Python’s behaviour and fixes a crash (#4019)
Preview style¶
Multiline dicts and lists that are the sole argument to a function are now indented less (#3964)
Multiline unpacked dicts and lists as the sole argument to a function are now also indented less (#3992)
In f-string debug expressions, quote types that are visible in the final string are now preserved (#4005)
Fix a bug where long
case
blocks were not split into multiple lines. Also enable general trailing comma rules oncase
blocks (#4024)Keep requiring two empty lines between module-level docstring and first function or class definition (#4028)
Add support for single-line format skip with other comments on the same line (#3959)
Configuration¶
Performance¶
Fix mypyc builds on arm64 on macOS (#4017)
Integrations¶
Black’s pre-commit integration will now run only on git hooks appropriate for a code formatter (#3940)
23.10.1¶
Highlights¶
Maintenance release to get a fix out for GitHub Action edge case (#3957)
Preview style¶
Packaging¶
Change Dockerfile to hatch + compile black (#3965)
Integrations¶
Documentation¶
It is known Windows documentation CI is broken https://github.com/psf/black/issues/3968
23.10.0¶
Stable style¶
Fix comments getting removed from inside parenthesized strings (#3909)
Preview style¶
Fix long lines with power operators getting split before the line length (#3942)
Long type hints are now wrapped in parentheses and properly indented when split across multiple lines (#3899)
Magic trailing commas are now respected in return types. (#3916)
Require one empty line after module-level docstrings. (#3932)
Treat raw triple-quoted strings as docstrings (#3947)
Configuration¶
Fix cache versioning logic when
BLACK_CACHE_DIR
is set (#3937)
Parser¶
Output¶
Integrations¶
The action output displayed in the job summary is now wrapped in Markdown (#3914)
23.9.1¶
Due to various issues, the previous release (23.9.0) did not include compiled mypyc wheels, which make Black significantly faster. These issues have now been fixed, and this release should come with compiled wheels once again.
There will be no wheels for Python 3.12 due to a bug in mypyc. We will provide 3.12 wheels in a future release as soon as the mypyc bug is fixed.
Packaging¶
Upgrade to mypy 1.5.1 (#3864)
Performance¶
Store raw tuples instead of NamedTuples in Black’s cache, improving performance and decreasing the size of the cache (#3877)
23.9.0¶
Preview style¶
Configuration¶
Black now applies exclusion and ignore logic before resolving symlinks (#3846)
Performance¶
Blackd¶
Fix an issue in
blackd
with single character input (#3558)
Integrations¶
Black now has an official pre-commit mirror. Swapping
https://github.com/psf/black
tohttps://github.com/psf/black-pre-commit-mirror
in your.pre-commit-config.yaml
will make Black about 2x faster (#3828)The
.black.env
folder specified byENV_PATH
will now be removed on the completion of the GitHub Action (#3759)
23.7.0¶
Highlights¶
Runtime support for Python 3.7 has been removed. Formatting 3.7 code will still be supported until further notice (#3765)
Stable style¶
Fix a bug where an illegal trailing comma was added to return type annotations using PEP 604 unions (#3735)
Fix several bugs and crashes where comments in stub files were removed or mishandled under some circumstances (#3745)
Fix a crash with multi-line magic comments like
type: ignore
within parentheses (#3740)Fix error in AST validation when Black removes trailing whitespace in a type comment (#3773)
Preview style¶
Configuration¶
The
--workers
argument to Black can now be specified via theBLACK_NUM_WORKERS
environment variable (#3743).pytest_cache
,.ruff_cache
and.vscode
are now excluded by default (#3691)Fix Black not honouring
pyproject.toml
settings when running--stdin-filename
and thepyproject.toml
found isn’t in the current working directory (#3719)Black will now error if
exclude
andextend-exclude
have invalid data types inpyproject.toml
, instead of silently doing the wrong thing (#3764)
Packaging¶
Parser¶
Add support for the new PEP 695 syntax in Python 3.12 (#3703)
Performance¶
Output¶
Blackd¶
The
blackd
argument parser now shows the default values for options in their help text (#3712)
Integrations¶
Black is now tested with
PYTHONWARNDEFAULTENCODING = 1
(#3763)Update GitHub Action to display black output in the job summary (#3688)
Documentation¶
23.3.0¶
Highlights¶
This release fixes a longstanding confusing behavior in Black’s GitHub action, where the version of the action did not determine the version of Black being run (issue #3382). In addition, there is a small bug fix around imports and a number of improvements to the preview style.
Please try out the
preview style
with black --preview
and tell us your feedback. All changes in the preview style are
expected to become part of Black’s stable style in January 2024.
Stable style¶
Import lines with
# fmt: skip
and# fmt: off
no longer have an extra blank line added when they are right after another import line (#3610)
Preview style¶
Add trailing commas to collection literals even if there’s a comment after the last entry (#3393)
async def
,async for
, andasync with
statements are now formatted consistently compared to their non-async version. (#3609)with
statements that contain two context managers will be consistently wrapped in parentheses (#3589)Let string splitters respect East Asian Width (#3445)
Now long string literals can be split after East Asian commas and periods (
、
U+3001 IDEOGRAPHIC COMMA,。
U+3002 IDEOGRAPHIC FULL STOP, &,
U+FF0C FULLWIDTH COMMA) besides before spaces (#3445)For stubs, enforce one blank line after a nested class with a body other than just
...
(#3564)Improve handling of multiline strings by changing line split behavior (#1879)
Parser¶
Added support for formatting files with invalid type comments (#3594)
Integrations¶
Documentation¶
Document that only the most recent release is supported for security issues; vulnerabilities should be reported through Tidelift (#3612)
23.1.0¶
Highlights¶
This is the first release of 2023, and following our stability policy, it comes with a number of improvements to our stable style, including improvements to empty line handling, removal of redundant parentheses in several contexts, and output that highlights implicitly concatenated strings better.
There are also many changes to the preview style; try out black --preview
and give us
feedback to help us set the stable style for next year.
In addition to style changes, Black now automatically infers the supported Python
versions from your pyproject.toml
file, removing the need to set Black’s target
versions separately.
Stable style¶
Introduce the 2023 stable style, which incorporates most aspects of last year’s preview style (#3418). Specific changes:
Enforce empty lines before classes and functions with sticky leading comments (#3302) (22.12.0)
Reformat empty and whitespace-only files as either an empty file (if no newline is present) or as a single newline character (if a newline is present) (#3348) (22.12.0)
Implicitly concatenated strings used as function args are now wrapped inside parentheses (#3307) (22.12.0)
Correctly handle trailing commas that are inside a line’s leading non-nested parens (#3370) (22.12.0)
--skip-string-normalization
/-S
now prevents docstring prefixes from being normalized as expected (#3168) (since 22.8.0)When using
--skip-magic-trailing-comma
or-C
, trailing commas are stripped from subscript expressions with more than 1 element (#3209) (22.8.0)Implicitly concatenated strings inside a list, set, or tuple are now wrapped inside parentheses (#3162) (22.8.0)
Fix a string merging/split issue when a comment is present in the middle of implicitly concatenated strings on its own line (#3227) (22.8.0)
Docstring quotes are no longer moved if it would violate the line length limit (#3044, #3430) (22.6.0)
Parentheses around return annotations are now managed (#2990) (22.6.0)
Remove unnecessary parentheses around awaited objects (#2991) (22.6.0)
Remove unnecessary parentheses in
with
statements (#2926) (22.6.0)Remove trailing newlines after code block open (#3035) (22.6.0)
Code cell separators
#%%
are now standardised to# %%
(#2919) (22.3.0)Remove unnecessary parentheses from
except
statements (#2939) (22.3.0)Remove unnecessary parentheses from tuple unpacking in
for
loops (#2945) (22.3.0)Avoid magic-trailing-comma in single-element subscripts (#2942) (22.3.0)
Fix a crash when a colon line is marked between
# fmt: off
and# fmt: on
(#3439)
Preview style¶
Format hex codes in unicode escape sequences in string literals (#2916)
Add parentheses around
if
-else
expressions (#2278)Improve performance on large expressions that contain many strings (#3467)
Fix a crash in preview style with assert + parenthesized string (#3415)
Fix crashes in preview style with walrus operators used in function return annotations and except clauses (#3423)
Fix a crash in preview advanced string processing where mixed implicitly concatenated regular and f-strings start with an empty span (#3463)
Fix a crash in preview advanced string processing where a standalone comment is placed before a dict’s value (#3469)
Fix an issue where extra empty lines are added when a decorator has
# fmt: skip
applied or there is a standalone comment between decorators (#3470)Do not put the closing quotes in a docstring on a separate line, even if the line is too long (#3430)
Long values in dict literals are now wrapped in parentheses; correspondingly unnecessary parentheses around short values in dict literals are now removed; long string lambda values are now wrapped in parentheses (#3440)
Fix two crashes in preview style involving edge cases with docstrings (#3451)
Exclude string type annotations from improved string processing; fix crash when the return type annotation is stringified and spans across multiple lines (#3462)
Wrap multiple context managers in parentheses when targeting Python 3.9+ (#3489)
Fix several crashes in preview style with walrus operators used in
with
statements or tuples (#3473)Fix an invalid quote escaping bug in f-string expressions where it produced invalid code. Implicitly concatenated f-strings with different quotes can now be merged or quote-normalized by changing the quotes used in expressions. (#3509)
Fix crash on
await (yield)
when Black is compiled with mypyc (#3533)
Configuration¶
Black now tries to infer its
--target-version
from the project metadata specified inpyproject.toml
(#3219)
Packaging¶
Upgrade mypyc from
0.971
to0.991
so mypycified Black can be built on armv7 (#3380)This also fixes some crashes while using compiled Black with a debug build of CPython
Drop specific support for the
tomli
requirement on 3.11 alpha releases, working around a bug that would cause the requirement not to be installed on any non-final Python releases (#3448)Black now depends on
packaging
version22.0
or later. This is required for new functionality that needs to parse part of the project metadata (#3219)
Output¶
Integrations¶
Documentation¶
Expand
vim-plug
installation instructions to offer more explicit options (#3468)
22.12.0¶
Preview style¶
Enforce empty lines before classes and functions with sticky leading comments (#3302)
Reformat empty and whitespace-only files as either an empty file (if no newline is present) or as a single newline character (if a newline is present) (#3348)
Implicitly concatenated strings used as function args are now wrapped inside parentheses (#3307)
For assignment statements, prefer splitting the right hand side if the left hand side fits on a single line (#3368)
Correctly handle trailing commas that are inside a line’s leading non-nested parens (#3370)
Configuration¶
Parser¶
Parsing support has been added for walruses inside generator expression that are passed as function args (for example,
any(match := my_re.match(text) for text in texts)
) (#3327).
Integrations¶
Vim plugin: Optionally allow using the system installation of Black via
let g:black_use_virtualenv = 0
(#3309)
22.10.0¶
Highlights¶
Runtime support for Python 3.6 has been removed. Formatting 3.6 code will still be supported until further notice.
Stable style¶
Fix a crash when
# fmt: on
is used on a different block level than# fmt: off
(#3281)
Preview style¶
Fix a crash when formatting some dicts with parenthesis-wrapped long string keys (#3262)
Configuration¶
Packaging¶
Executables made with PyInstaller will no longer crash when formatting several files at once on macOS. Native x86-64 executables for macOS are available once again. (#3275)
Hatchling is now used as the build backend. This will not have any effect for users who install Black with its wheels from PyPI. (#3233)
Faster compiled wheels are now available for CPython 3.11 (#3276)
Blackd¶
Windows style (CRLF) newlines will be preserved (#3257).
Integrations¶
22.8.0¶
Highlights¶
Python 3.11 is now supported, except for blackd as aiohttp does not support 3.11 as of publishing (#3234)
This is the last release that supports running Black on Python 3.6 (formatting 3.6 code will continue to be supported until further notice)
Reword the stability policy to say that we may, in rare cases, make changes that affect code that was not previously formatted by Black (#3155)
Stable style¶
Preview style¶
Single-character closing docstring quotes are no longer moved to their own line as this is invalid. This was a bug introduced in version 22.6.0. (#3166)
--skip-string-normalization
/-S
now prevents docstring prefixes from being normalized as expected (#3168)When using
--skip-magic-trailing-comma
or-C
, trailing commas are stripped from subscript expressions with more than 1 element (#3209)Implicitly concatenated strings inside a list, set, or tuple are now wrapped inside parentheses (#3162)
Fix a string merging/split issue when a comment is present in the middle of implicitly concatenated strings on its own line (#3227)
Blackd¶
blackd
now supports enabling the preview style via theX-Preview
header (#3217)
Configuration¶
Black now uses the presence of debug f-strings to detect target version (#3215)
Fix misdetection of project root and verbose logging of sources in cases involving
--stdin-filename
(#3216)Immediate
.gitignore
files in source directories given on the command line are now also respected, previously only.gitignore
files in the project root and automatically discovered directories were respected (#3237)
Documentation¶
Recommend using BlackConnect in IntelliJ IDEs (#3150)
Integrations¶
Output¶
Parser¶
Type comments are now included in the AST equivalence check consistently so accidental deletion raises an error. Though type comments can’t be tracked when running on PyPy 3.7 due to standard library limitations. (#2874)
Performance¶
Reduce Black’s startup time when formatting a single file by 15-30% (#3211)
22.6.0¶
Style¶
Fix unstable formatting involving
#fmt: skip
and# fmt:skip
comments (notice the lack of spaces) (#2970)
Preview style¶
Docstring quotes are no longer moved if it would violate the line length limit (#3044)
Parentheses around return annotations are now managed (#2990)
Remove unnecessary parentheses around awaited objects (#2991)
Remove unnecessary parentheses in
with
statements (#2926)Remove trailing newlines after code block open (#3035)
Integrations¶
Add
scripts/migrate-black.py
script to ease introduction of Black to a Git project (#3038)
Output¶
Output Python version and implementation as part of
--version
flag (#2997)
Packaging¶
Use
tomli
instead oftomllib
on Python 3.11 builds wheretomllib
is not available (#2987)
Parser¶
Vim Plugin¶
Fix
strtobool
function. It didn’t parse true/on/false/off. (#3025)
22.3.0¶
Preview style¶
Configuration¶
Documentation¶
Update pylint config documentation (#2931)
Integrations¶
Move test to disable plugin in Vim/Neovim, which speeds up loading (#2896)
Output¶
In verbose mode, log when Black is using user-level config (#2861)
Packaging¶
Fix Black to work with Click 8.1.0 (#2966)
On Python 3.11 and newer, use the standard library’s
tomllib
instead oftomli
(#2903)black-primer
, the deprecated internal devtool, has been removed and copied to a separate repository (#2924)
Parser¶
Black can now parse starred expressions in the target of
for
andasync for
statements, e.gfor item in *items_1, *items_2: pass
(#2879).
22.1.0¶
At long last, Black is no longer a beta product! This is the first non-beta release and the first release covered by our new stability policy.
Highlights¶
Style¶
Deprecate
--experimental-string-processing
and move the functionality under--preview
(#2789)For stubs, one blank line between class attributes and methods is now kept if there’s at least one pre-existing blank line (#2736)
Black now normalizes string prefix order (#2297)
Remove spaces around power operators if both operands are simple (#2726)
Work around bug that causes unstable formatting in some cases in the presence of the magic trailing comma (#2807)
Use parentheses for attribute access on decimal float and int literals (#2799)
Don’t add whitespace for attribute access on hexadecimal, binary, octal, and complex literals (#2799)
Treat blank lines in stubs the same inside top-level
if
statements (#2820)Fix unstable formatting with semicolons and arithmetic expressions (#2817)
Fix unstable formatting around magic trailing comma (#2572)
Parser¶
Fix mapping cases that contain as-expressions, like
case {"key": 1 | 2 as password}
(#2686)Fix cases that contain multiple top-level as-expressions, like
case 1 as a, 2 as b
(#2716)Fix call patterns that contain as-expressions with keyword arguments, like
case Foo(bar=baz as quux)
(#2749)Tuple unpacking on
return
andyield
constructs now implies 3.8+ (#2700)Unparenthesized tuples on annotated assignments (e.g
values: Tuple[int, ...] = 1, 2, 3
) now implies 3.8+ (#2708)Fix handling of standalone
match()
orcase()
when there is a trailing newline or a comment inside of the parentheses. (#2760)from __future__ import annotations
statement now implies Python 3.7+ (#2690)
Performance¶
Configuration¶
Do not accept bare carriage return line endings in pyproject.toml (#2408)
Add configuration option (
python-cell-magics
) to format cells with custom magics in Jupyter Notebooks (#2744)Allow setting custom cache directory on all platforms with environment variable
BLACK_CACHE_DIR
(#2739).Enable Python 3.10+ by default, without any extra need to specify
--target-version=py310
. (#2758)Make passing
SRC
or--code
mandatory and mutually exclusive (#2804)
Output¶
Improve error message for invalid regular expression (#2678)
Improve error message when parsing fails during AST safety check by embedding the underlying SyntaxError (#2693)
No longer color diff headers white as it’s unreadable in light themed terminals (#2691)
Text coloring added in the final statistics (#2712)
Verbose mode also now describes how a project root was discovered and which paths will be formatted. (#2526)
Packaging¶
Integrations¶
Update GitHub action to support containerized runs (#2748)
Documentation¶
21.12b0¶
Black¶
Fix determination of f-string expression spans (#2654)
Fix bad formatting of error messages about EOF in multi-line statements (#2343)
Functions and classes in blocks now have more consistent surrounding spacing (#2472)
Jupyter Notebook support¶
Python 3.10 support¶
Point users to using
--target-version py310
if we detect 3.10-only syntax (#2668)Fix
match
statements with open sequence subjects, likematch a, b:
ormatch a, *b:
(#2639) (#2659)Fix
match
/case
statements that containmatch
/case
soft keywords multiple times, likematch re.match()
(#2661)Fix
case
statements with an inline body (#2665)Fix styling of starred expressions inside
match
subject (#2667)Fix parser error location on invalid syntax in a
match
statement (#2649)Fix Python 3.10 support on platforms without ProcessPoolExecutor (#2631)
Improve parsing performance on code that uses
match
under--target-version py310
up to ~50% (#2670)
Packaging¶
21.11b1¶
Black¶
Bumped regex version minimum to 2021.4.4 to fix Pattern class usage (#2621)
21.11b0¶
Black¶
Warn about Python 2 deprecation in more cases by improving Python 2 only syntax detection (#2592)
Add experimental PyPy support (#2559)
Add partial support for the match statement. As it’s experimental, it’s only enabled when
--target-version py310
is explicitly specified (#2586)Add support for parenthesized with (#2586)
Declare support for Python 3.10 for running Black (#2562)
Integrations¶
21.10b0¶
Black¶
Document stability policy, that will apply for non-beta releases (#2529)
Add new
--workers
parameter (#2514)Fixed feature detection for positional-only arguments in lambdas (#2532)
Bumped typed-ast version minimum to 1.4.3 for 3.10 compatibility (#2519)
Fixed a Python 3.10 compatibility issue where the loop argument was still being passed even though it has been removed (#2580)
Deprecate Python 2 formatting support (#2523)
Blackd¶
Black-Primer¶
Integrations¶
21.9b0¶
Packaging¶
21.8b0¶
Black¶
Add support for formatting Jupyter Notebook files (#2357)
Move from
appdirs
dependency toplatformdirs
(#2375)Present a more user-friendly error if .gitignore is invalid (#2414)
The failsafe for accidentally added backslashes in f-string expressions has been hardened to handle more edge cases during quote normalization (#2437)
Avoid changing a function return type annotation’s type to a tuple by adding a trailing comma (#2384)
Parsing support has been added for unparenthesized walruses in set literals, set comprehensions, and indices (#2447).
Pin
setuptools-scm
build-time dependency version (#2457)Exclude typing-extensions version 3.10.0.1 due to it being broken on Python 3.10 (#2460)
Blackd¶
Replace sys.exit(-1) with raise ImportError as it plays more nicely with tools that scan installed packages (#2440)
Integrations¶
The provided pre-commit hooks no longer specify
language_version
to avoid overridingdefault_language_version
(#2430)
21.7b0¶
Black¶
Configuration files using TOML features higher than spec v0.5.0 are now supported (#2301)
Add primer support and test for code piped into black via STDIN (#2315)
Fix internal error when
FORCE_OPTIONAL_PARENTHESES
feature is enabled (#2332)Accept empty stdin (#2346)
Provide a more useful error when parsing fails during AST safety checks (#2304)
Docker¶
Add new
latest_release
tag automation to follow latest black release on docker images (#2374)
Integrations¶
The vim plugin now searches upwards from the directory containing the current buffer instead of the current working directory for pyproject.toml. (#1871)
The vim plugin now reads the correct string normalization option in pyproject.toml (#1869)
The vim plugin no longer crashes Black when there’s boolean values in pyproject.toml (#1869)
21.6b0¶
Black¶
Fix failure caused by
fmt: skip
and indentation (#2281)Account for += assignment when deciding whether to split string (#2312)
Correct max string length calculation when there are string operators (#2292)
Fixed option usage when using the
--code
flag (#2259)Do not call
uvloop.install()
when Black is used as a library (#2303)Added
--required-version
option to require a specific version to be running (#2300)Fix incorrect custom breakpoint indices when string group contains fake f-strings (#2311)
Fix regression where
R
prefixes would be lowercased for docstrings (#2285)Fix handling of named escapes (
\N{...}
) when--experimental-string-processing
is used (#2319)
Integrations¶
The official Black action now supports choosing what version to use, and supports the major 3 OSes. (#1940)
21.5b2¶
Black¶
A space is no longer inserted into empty docstrings (#2249)
Fix handling of .gitignore files containing non-ASCII characters on Windows (#2229)
Respect
.gitignore
files in all levels, not onlyroot/.gitignore
file (apply.gitignore
rules likegit
does) (#2225)Restored compatibility with Click 8.0 on Python 3.6 when LANG=C used (#2227)
Add extra uvloop install + import support if in python env (#2258)
Fix –experimental-string-processing crash when matching parens are not found (#2283)
Make sure to split lines that start with a string operator (#2286)
Fix regular expression that black uses to identify f-expressions (#2287)
Blackd¶
Add a lower bound for the
aiohttp-cors
dependency. Only 0.4.0 or higher is supported. (#2231)
Packaging¶
Documentation¶
Add discussion of magic comments to FAQ page (#2272)
--experimental-string-processing
will be enabled by default in the future (#2273)Fix typos discovered by codespell (#2228)
Fix Vim plugin installation instructions. (#2235)
Add new Frequently Asked Questions page (#2247)
Fix encoding + symlink issues preventing proper build on Windows (#2262)
21.5b1¶
Black¶
Refactor
src/black/__init__.py
into many files (#2206)
Documentation¶
Replaced all remaining references to the
master
branch with themain
branch. Some additional changes in the source code were also made. (#2210)Significantly reorganized the documentation to make much more sense. Check them out by heading over to the stable docs on RTD. (#2174)
21.5b0¶
Black¶
Black-Primer¶
Add
--no-diff
to black-primer to suppress formatting changes (#2187)
21.4b2¶
Black¶
Fix crash if the user configuration directory is inaccessible. (#2158)
Clarify circumstances in which Black may change the AST (#2159)
Allow
.gitignore
rules to be overridden by specifyingexclude
inpyproject.toml
or on the command line. (#2170)
Packaging¶
Install
primer.json
(used byblack-primer
by default) with black. (#2154)
21.4b1¶
Black¶
Fix crash on docstrings ending with “\ “. (#2142)
Fix crash when atypical whitespace is cleaned out of dostrings (#2120)
Reflect the
--skip-magic-trailing-comma
and--experimental-string-processing
flags in the name of the cache file. Without this fix, changes in these flags would not take effect if the cache had already been populated. (#2131)Don’t remove necessary parentheses from assignment expression containing assert / return statements. (#2143)
Packaging¶
Bump pathspec to >= 0.8.1 to solve invalid .gitignore exclusion handling
21.4b0¶
Black¶
Fixed a rare but annoying formatting instability created by the combination of optional trailing commas inserted by
Black
and optional parentheses looking at pre-existing “magic” trailing commas. This fixes issue #1629 and all of its many many duplicates. (#2126)Black
now processes one-line docstrings by stripping leading and trailing spaces, and adding a padding space when needed to break up “”””. (#1740)Black
now cleans up leading non-breaking spaces in comments (#2092)Black
now respects--skip-string-normalization
when normalizing multiline docstring quotes (#1637)Black
no longer removes all empty lines between non-function code and decorators when formatting typing stubs. NowBlack
enforces a single empty line. (#1646)Black
no longer adds an incorrect space after a parenthesized assignment expression in if/while statements (#1655)Added
--skip-magic-trailing-comma
/-C
to avoid using trailing commas as a reason to split lines (#1824)fixed a crash when PWD=/ on POSIX (#1631)
fixed “I/O operation on closed file” when using –diff (#1664)
Prevent coloured diff output being interleaved with multiple files (#1673)
Added support for PEP 614 relaxed decorator syntax on python 3.9 (#1711)
Added parsing support for unparenthesized tuples and yield expressions in annotated assignments (#1835)
added
--extend-exclude
argument (PR #2005)speed up caching by avoiding pathlib (#1950)
--diff
correctly indicates when a file doesn’t end in a newline (#1662)Added
--stdin-filename
argument to allow stdin to respect--force-exclude
rules (#1780)Lines ending with
fmt: skip
will now be not formatted (#1800)PR #2053: Black no longer relies on typed-ast for Python 3.8 and higher
PR #2053: Python 2 support is now optional, install with
python3 -m pip install black[python2]
to maintain support.Exclude
venv
directory by default (#1683)Fixed “Black produced code that is not equivalent to the source” when formatting Python 2 docstrings (#2037)
Packaging¶
Self-contained native Black binaries are now provided for releases via GitHub Releases (#1743)
20.8b1¶
Packaging¶
explicitly depend on Click 7.1.2 or newer as
Black
no longer works with versions older than 7.0
20.8b0¶
Black¶
re-implemented support for explicit trailing commas: now it works consistently within any bracket pair, including nested structures (#1288 and duplicates)
Black
now reindents docstrings when reindenting code around it (#1053)Black
now shows colored diffs (#1266)Black
is now packaged using ‘py3’ tagged wheels (#1388)Black
now supports Python 3.8 code, e.g. star expressions in return statements (#1121)Black
no longer normalizes capital R-string prefixes as those have a community-accepted meaning (#1244)Black
now uses exit code 2 when specified configuration file doesn’t exit (#1361)Black
now works on AWS Lambda (#1141)added
--force-exclude
argument (#1032)removed deprecated
--py36
option (#1236)fixed
--diff
output when EOF is encountered (#526)fixed
# fmt: off
handling around decorators (#560)fixed unstable formatting with some
# type: ignore
comments (#1113)fixed invalid removal on organizing brackets followed by indexing (#1575)
introduced
black-primer
, a CI tool that allows us to run regression tests against existing open source users of Black (#1402)introduced property-based fuzzing to our test suite based on Hypothesis and Hypothersmith (#1566)
implemented experimental and disabled by default long string rewrapping (#1132), hidden under a
--experimental-string-processing
flag while it’s being worked on; this is an undocumented and unsupported feature, you lose Internet points for depending on it (#1609)
Vim plugin¶
prefer virtualenv packages over global packages (#1383)
19.10b0¶
added support for PEP 572 assignment expressions (#711)
added support for PEP 570 positional-only arguments (#943)
added support for async generators (#593)
added support for pre-splitting collections by putting an explicit trailing comma inside (#826)
added
black -c
as a way to format code passed from the command line (#761)–safe now works with Python 2 code (#840)
fixed grammar selection for Python 2-specific code (#765)
fixed feature detection for trailing commas in function definitions and call sites (#763)
# fmt: off
/# fmt: on
comment pairs placed multiple times within the same block of code now behave correctly (#1005)Black no longer crashes on Windows machines with more than 61 cores (#838)
Black no longer crashes on standalone comments prepended with a backslash (#767)
Black no longer crashes on
from
…import
blocks with comments (#829)Black no longer crashes on Python 3.7 on some platform configurations (#494)
Black no longer fails on comments in from-imports (#671)
Black no longer fails when the file starts with a backslash (#922)
Black no longer merges regular comments with type comments (#1027)
Black no longer splits long lines that contain type comments (#997)
removed unnecessary parentheses around
yield
expressions (#834)added parentheses around long tuples in unpacking assignments (#832)
added parentheses around complex powers when they are prefixed by a unary operator (#646)
fixed bug that led Black format some code with a line length target of 1 (#762)
Black no longer introduces quotes in f-string subexpressions on string boundaries (#863)
if Black puts parenthesis around a single expression, it moves comments to the wrapped expression instead of after the brackets (#872)
blackd
now returns the version of Black in the response headers (#1013)blackd
can now output the diff of formats on source code when theX-Diff
header is provided (#969)
19.3b0¶
new option
--target-version
to control which Python versions Black-formatted code should target (#618)deprecated
--py36
(use--target-version=py36
instead) (#724)Black no longer normalizes numeric literals to include
_
separators (#696)long
del
statements are now split into multiple lines (#698)type comments are no longer mangled in function signatures
improved performance of formatting deeply nested data structures (#509)
Black now properly formats multiple files in parallel on Windows (#632)
Black now creates cache files atomically which allows it to be used in parallel pipelines (like
xargs -P8
) (#673)Black now correctly indents comments in files that were previously formatted with tabs (#262)
blackd
now supports CORS (#622)
18.9b0¶
numeric literals are now formatted by Black (#452, #461, #464, #469):
numeric literals are normalized to include
_
separators on Python 3.6+ codeadded
--skip-numeric-underscore-normalization
to disable the above behavior and leave numeric underscores as they were in the inputcode with
_
in numeric literals is recognized as Python 3.6+most letters in numeric literals are lowercased (e.g., in
1e10
,0x01
)hexadecimal digits are always uppercased (e.g.
0xBADC0DE
)
added
blackd
, see its documentation for more info (#349)adjacent string literals are now correctly split into multiple lines (#463)
trailing comma is now added to single imports that don’t fit on a line (#250)
cache is now populated when
--check
is successful for a file which speeds up consecutive checks of properly formatted unmodified files (#448)whitespace at the beginning of the file is now removed (#399)
fixed mangling pweave and Spyder IDE special comments (#532)
fixed unstable formatting when unpacking big tuples (#267)
fixed parsing of
__future__
imports with renames (#389)fixed scope of
# fmt: off
when directly precedingyield
and other nodes (#385)fixed formatting of lambda expressions with default arguments (#468)
fixed
async for
statements: Black no longer breaks them into separate lines (#372)note: the Vim plugin stopped registering
,=
as a default chord as it turned out to be a bad idea (#415)
18.6b4¶
hotfix: don’t freeze when multiple comments directly precede
# fmt: off
(#371)
18.6b3¶
typing stub files (
.pyi
) now have blank lines added after constants (#340)# fmt: off
and# fmt: on
are now much more dependable:made Click not fail on invalid environments; note that Click is right but the likelihood we’ll need to access non-ASCII file paths when dealing with Python source code is low (#277)
fixed improper formatting of f-strings with quotes inside interpolated expressions (#322)
fixed unnecessary slowdown when long list literals where found in a file
fixed unnecessary slowdown on AST nodes with very many siblings
fixed cannibalizing backslashes during string normalization
fixed a crash due to symbolic links pointing outside of the project directory (#338)
18.6b2¶
18.6b1¶
18.6b0¶
added
--include
and--exclude
(#270)added
--skip-string-normalization
(#118)added
--verbose
(#283)the header output in
--diff
now actually conforms to the unified diff specfixed long trivial assignments being wrapped in unnecessary parentheses (#273)
fixed unnecessary parentheses when a line contained multiline strings (#232)
fixed stdin handling not working correctly if an old version of Click was used (#276)
Black now preserves line endings when formatting a file in place (#258)
18.5b1¶
added
--pyi
(#249)added
--py36
(#249)Python grammar pickle caches are stored with the formatting caches, making Black work in environments where site-packages is not user-writable (#192)
Black now enforces a PEP 257 empty line after a class-level docstring (and/or fields) and the first method
fixed invalid code produced when standalone comments were present in a trailer that was omitted from line splitting on a large expression (#237)
fixed optional parentheses being removed within
# fmt: off
sections (#224)fixed invalid code produced when stars in very long imports were incorrectly wrapped in optional parentheses (#234)
fixed unstable formatting when inline comments were moved around in a trailer that was omitted from line splitting on a large expression (#238)
fixed extra empty line between a class declaration and the first method if no class docstring or fields are present (#219)
fixed extra empty line between a function signature and an inner function or inner class (#196)
18.5b0¶
call chains are now formatted according to the fluent interfaces style (#67)
data structure literals (tuples, lists, dictionaries, and sets) are now also always exploded like imports when they don’t fit in a single line (#152)
slices are now formatted according to PEP 8 (#178)
parentheses are now also managed automatically on the right-hand side of assignments and return statements (#140)
math operators now use their respective priorities for delimiting multiline expressions (#148)
optional parentheses are now omitted on expressions that start or end with a bracket and only contain a single operator (#177)
empty parentheses in a class definition are now removed (#145, #180)
string prefixes are now standardized to lowercase and
u
is removed on Python 3.6+ only code and Python 2.7+ code with theunicode_literals
future import (#188, #198, #199)typing stub files (
.pyi
) are now formatted in a style that is consistent with PEP 484 (#207, #210)progress when reformatting many files is now reported incrementally
fixed trailers (content with brackets) being unnecessarily exploded into their own lines after a dedented closing bracket (#119)
fixed an invalid trailing comma sometimes left in imports (#185)
fixed non-deterministic formatting when multiple pairs of removable parentheses were used (#183)
fixed multiline strings being unnecessarily wrapped in optional parentheses in long assignments (#215)
fixed not splitting long from-imports with only a single name
fixed Python 3.6+ file discovery by also looking at function calls with unpacking. This fixed non-deterministic formatting if trailing commas where used both in function signatures with stars and function calls with stars but the former would be reformatted to a single line.
fixed crash on dealing with optional parentheses (#193)
fixed “is”, “is not”, “in”, and “not in” not considered operators for splitting purposes
fixed crash when dead symlinks where encountered
18.4a4¶
don’t populate the cache on
--check
(#175)
18.4a3¶
added a “cache”; files already reformatted that haven’t changed on disk won’t be reformatted again (#109)
--check
and--diff
are no longer mutually exclusive (#149)generalized star expression handling, including double stars; this fixes multiplication making expressions “unsafe” for trailing commas (#132)
Black no longer enforces putting empty lines behind control flow statements (#90)
Black now splits imports like “Mode 3 + trailing comma” of isort (#127)
fixed comment indentation when a standalone comment closes a block (#16, #32)
fixed standalone comments receiving extra empty lines if immediately preceding a class, def, or decorator (#56, #154)
fixed
--diff
not showing entire path (#130)fixed parsing of complex expressions after star and double stars in function calls (#2)
fixed invalid splitting on comma in lambda arguments (#133)
fixed missing splits of ternary expressions (#141)
18.4a2¶
18.4a1¶
18.4a0¶
added
--diff
(#87)add line breaks before all delimiters, except in cases like commas, to better comply with PEP 8 (#73)
standardize string literals to use double quotes (almost) everywhere (#75)
fixed handling of standalone comments within nested bracketed expressions; Black will no longer produce super long lines or put all standalone comments at the end of the expression (#22)
fixed 18.3a4 regression: don’t crash and burn on empty lines with trailing whitespace (#80)
fixed 18.3a4 regression:
# yapf: disable
usage as trailing comment would cause Black to not emit the rest of the file (#95)when CTRL+C is pressed while formatting many files, Black no longer freaks out with a flurry of asyncio-related exceptions
only allow up to two empty lines on module level and only single empty lines within functions (#74)
18.3a4¶
# fmt: off
and# fmt: on
are implemented (#5)automatic detection of deprecated Python 2 forms of print statements and exec statements in the formatted file (#49)
use proper spaces for complex expressions in default values of typed function arguments (#60)
only return exit code 1 when –check is used (#50)
don’t remove single trailing commas from square bracket indexing (#59)
don’t omit whitespace if the previous factor leaf wasn’t a math operator (#55)
omit extra space in kwarg unpacking if it’s the first argument (#46)
omit extra space in Sphinx auto-attribute comments (#68)
18.3a3¶
18.3a2¶
changed positioning of binary operators to occur at beginning of lines instead of at the end, following a recent change to PEP 8 (#21)
ignore empty bracket pairs while splitting. This avoids very weirdly looking formattings (#34, #35)
remove a trailing comma if there is a single argument to a call
if top level functions were separated by a comment, don’t put four empty lines after the upper function
fixed unstable formatting of newlines with imports
fixed unintentional folding of post scriptum standalone comments into last statement if it was a simple statement (#18, #28)
fixed missing space in numpy-style array indexing (#33)
fixed spurious space after star-based unary expressions (#31)
18.3a1¶
added
--check
only put trailing commas in function signatures and calls if it’s safe to do so. If the file is Python 3.6+ it’s always safe, otherwise only safe if there are no
*args
or**kwargs
used in the signature or call. (#8)fixed invalid splitting after comma on unpacked variables in for-loops (#23)
fixed spurious space in parenthesized set expressions (#7)
fixed spurious space after opening parentheses and in default arguments (#14, #17)
fixed spurious space after unary operators when the operand was a complex expression (#15)
18.3a0¶
first published version, Happy 🍰 Day 2018!
alpha quality
date-versioned (see: https://calver.org/)
Comments¶
Black does not format comment contents, but it enforces two spaces between code and a comment on the same line, and a space before the comment text begins. Some types of comments that require specific spacing rules are respected: shebangs (
#! comment
), doc comments (#: comment
), section comments with long runs of hashes, and Spyder cells. Non-breaking spaces after hashes are also preserved. Comments may sometimes be moved because of formatting changes, which can break tools that assign special meaning to them. See AST before and after formatting for more discussion.