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:

[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](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:

https://img.shields.io/badge/code%20style-black-000000.svg

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.

Black reformats entire files in place. It doesn’t reformat lines that end with # fmt: skip or blocks that start with # fmt: off and end with # fmt: on. # 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. It also recognizes YAPF’s block comments to the same effect, as a courtesy for straddling code.

The rest of 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 line 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#

If you use Flake8, you have a few options:

  1. Recommended is using Bugbear and enabling 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
    ...
    select = C,E,F,W,B,B950
    extend-ignore = E203, E501
    

    The rationale for E950 is explained in Bugbear’s documentation.

  2. For a minimally compatible config:

    [flake8]
    max-line-length = 88
    extend-ignore = E203
    

An explanation of why E203 is disabled can be found in the Slices section of this page.

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. The other exception is that it will remove any empty lines immediately following a statement that introduces a new indentation level.

# in:

def foo():

    print("All the newlines above me should be deleted!")


if condition:

    print("No newline above me!")

    print("There is a newline above me, and that's OK!")


class Point:

    x: int
    y: int

# out:

def foo():
    print("All the newlines above me should be deleted!")


if condition:
    print("No newline above me!")

    print("There is a newline above me, and that's OK!")


class Point:
    x: int
    y: int

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.

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.

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 ... over pass;

  • 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.

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:

  1. 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.

  2. 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.

  3. 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#

Warning

Changes to this document often aren’t tied and don’t relate to releases of Black. It’s recommended that you read the latest version available.

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())
    ...
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!

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 line breaks#

For assignment expressions, Black now prefers to split and wrap the right side of the assignment instead of left side. For example:

some_dict[
    "with_a_long_key"
] = some_looooooooong_module.some_looooooooooooooong_function_name(
    first_argument, second_argument, third_argument
)

will be changed to:

some_dict["with_a_long_key"] = (
    some_looooooooong_module.some_looooooooooooooong_function_name(
        first_argument, second_argument, third_argument
    )
)
Improved parentheses management#

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", "")

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 flag is exempt from this policy. There are no guarantees around the stability of the output with that flag passed into Black. This flag is intended for allowing experimentation with the proposed changes to the Black code style.

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.7+ to run. If you want to format Jupyter Notebooks, install with pip install "black[jupyter]".

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#

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}
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).

-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 should include all versions that your code supports. If you support Python 3.7 through 3.10, you should write:

$ black -t py37 -t py38 -t py39 -t py310

In a configuration file, you can write:

target-version = ["py37", "py38", "py39", "py310"]

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.

-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 may be added to Black’s main functionality in the next major release. Read more about our preview style.

--check#

Passing --check will make Black 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

$ 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#

Passing --diff will make Black print out diffs that 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.

--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, 23.9.0 (compiled: yes)
$ black --required-version 23.9.0 -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.

--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). Exclusions are calculated first, inclusions later.

--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). Exclusions are calculated first, inclusions later.

--extend-exclude#

Like --exclude, but adds additional files and directories on top of the excluded ones. Useful if you simply want to add to the default.

--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.

-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.

-q, --quiet#

Passing -q / --quiet will cause Black to 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#

Passing -v / --verbose will cause Black to also emit messages about files that were not changed or were ignored due to exclusion patterns. If Black is using a configuration file, a blue 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, 23.9.0
--config#

Read configuration options from a configuration file. See below for more details on the configuration file.

-h, --help#

Show available command-line options and exit.

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 -c / --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 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 the XDG_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 blue 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-Fast-Or-Safe: if set to fast, blackd will act as Black does when passed the --fast command line flag.

  • X-Python-Variant: if set to pyi, 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 with py. For example, to request code that is compatible with Python 3.5 and 3.6, set the header to py3.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 the Content-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.

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:

  1. Using the built-in Black integration (PyCharm 2023.2 and later). This option is the simplest to set up.

  2. 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.

  3. As external tool.

  4. As file watcher.

Built-in Black integration#
  1. Install black.

    $ pip install black
    
  2. Go to Preferences or Settings -> Tools -> Black and configure Black to your liking.

As local server#
  1. Install Black with the d extra.

    $ pip install 'black[d]'
    
  2. Install BlackConnect IntelliJ IDEs plugin.

  3. Open plugin configuration in PyCharm/IntelliJ IDEA

    On macOS:

    PyCharm -> Preferences -> Tools -> BlackConnect

    On Windows / Linux / BSD:

    File -> Settings -> Tools -> BlackConnect

  4. In Local Instance (shared between projects) section:

    1. Check Start local blackd instance when plugin loads.

    2. Press the Detect button near Path input. The plugin should detect the blackd executable.

  5. In Trigger Settings section check Trigger on code reformat to enable code reformatting with Black.

  6. Format the currently opened file by selecting Code -> Reformat Code or using a shortcut.

  7. Optionally, to run Black on every file save:

    • In Trigger Settings section of plugin configuration check Trigger when saving changed files.

As external tool#
  1. Install black.

    $ pip install black
    
  2. 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.

  3. Open External tools in PyCharm/IntelliJ IDEA

    On macOS:

    PyCharm -> Preferences -> Tools -> External Tools

    On Windows / Linux / BSD:

    File -> Settings -> Tools -> External Tools

  4. 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$"

  5. 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#
  1. Install black.

    $ pip install black
    
  2. 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.

  3. Make sure you have the File Watchers plugin installed.

  4. 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:

  1. In menubar navigate to Edit -> Preferences -> Editor -> Reformatting.

  2. Set Auto-Reformat from disable (default) to Line after edit or Whole files before save.

  3. Set Reformatter from PEP8 (default) to Black.

Project Properties#

If you want to just reformat for a specific project and not intervene with Wing IDE global setting, follow these steps:

  1. In menubar navigate to Project -> Project Properties -> Options.

  2. Set Auto-Reformat from Use Preferences setting (default) to Line after edit or Whole files before save.

  3. Set Reformatter from Use Preferences setting (default) to Black.

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 to 0)

  • g:black_linelength (defaults to 88)

  • g:black_skip_string_normalization (defaults to 0)

  • g:black_skip_magic_trailing_comma (defaults to 0)

  • g:black_virtualenv (defaults to ~/.vim/black or ~/.local/share/nvim/black)

  • g:black_use_virtualenv (defaults to 1)

  • g:black_target_version (defaults to "")

  • g:black_quiet (defaults to 0)

  • g:black_preview (defaults to 0)

Installation#

This plugin requires Vim 7.0+ built with Python 3.7+ support. It needs Python 3.7 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#
  1. Install ale

  2. Install black

  3. 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>
  1. Go to edit > preferences > plugins

  2. Search for external tools and activate it.

  3. In Tools menu -> Manage external tools

  4. Add a new tool using + button.

  5. 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#
SublimeText 3#

Use sublack plugin.

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#

Use Thonny-black-code-format.

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. This can be any valid version specifier or just the version number if you want an exact version. 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"

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: 23.9.0
    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: 23.9.0
    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.

# 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
Flake8#

Flake8 is a code linter. It warns you of syntax errors, possible bugs, stylistic errors, etc. For the most part, Flake8 follows PEP 8 when warning about stylistic errors. There are a few deviations that cause incompatibilities with Black.

Configuration#
max-line-length = 88
extend-ignore = E203
Why those options above?#

In some cases, as determined by PEP 8, Black will enforce an equal amount of whitespace around slice operators. Due to this, Flake8 will raise E203 whitespace before ':' warnings. Since this warning is not PEP 8 compliant, Flake8 should be configured to ignore it via extend-ignore = E203.

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.

Also, as like with isort, flake8 should be configured to allow lines up to the length limit of 88, Black’s default. This explains max-line-length = 88.

Formats#
.flake8
[flake8]
max-line-length = 88
extend-ignore = E203
setup.cfg
[flake8]
max-line-length = 88
extend-ignore = E203
tox.ini
[flake8]
max-line-length = 88
extend-ignore = E203
Pylint#

Pylint is also a code linter like Flake8. It has the same checks as flake8 and more. In particular, it has more formatting checks regarding style conventions like variable naming. With so many checks, Pylint is bound to have some mixed feelings about Black’s formatting style.

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"
pycodestyle#

pycodestyle is also a code linter like Flake8.

Configuration#
max-line-length = 88
ignore = E203
Why those options above?#

pycodestyle should be configured to only complain about lines that surpass 88 characters via max_line_length = 88.

See Why are Flake8’s E203 and W503 violated?

Formats#
setup.cfg
[pycodestyle]
ignore = E203
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 will be stable for the releases made in the same year (other than unintentional bugs). 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’s TransformerManager 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 are Flake8’s E203 and W503 violated?#

Because they go against PEP 8. E203 falsely triggers on list slices, and adhering to W503 hinders readability because operators are misaligned. Disable W503 and enable the disabled-by-default counterpart W504. E203 should be disabled while changes are still discussed.

Which Python versions does Black support?#

Currently the runtime requires Python 3.7-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.6 was removed in version 22.10.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.7 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
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 main

PR commit with main merged

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:

  1. the issue is waiting for triage

  2. 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 or S: awaiting response)

  3. confirmed - the issue can reproduced and necessary details have been provided

  4. discussion - initial triage has been done and now the general details on how the issue should be best resolved are being hashed out

  5. awaiting fix - no further discussion on the issue is necessary and a resolving PR is the next step

  6. 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:

  1. the issue is waiting for triage

  2. identified - has been marked with a type label and other relevant labels

  3. 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

  4. accepted & awaiting PR - it’s been determined the suggested changes are OK and a PR would be welcomed (S: accepted)

  5. 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.

To cut a release:

  1. Determine the release’s version number

    • Black follows the CalVer versioning standard using the YY.M.N format

      • So unless there already has been a release during this month, N should be 0

    • Example: the first release in January, 2022 → 22.1.0

  2. File a PR editing CHANGES.md and the docs to version the latest changes

    1. Replace the ## Unreleased header with the version number

    2. Remove any empty sections for the current release

    3. (optional) Read through and copy-edit the changelog (eg. by moving entries, fixing typos, or rephrasing entries)

    4. 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)

    5. Add a new empty template for the next release above (template below)

    6. Update references to the latest version in Version control integration and The basics

  3. 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

  4. Draft a new GitHub Release

    1. Click Choose a tag and type in the version number, then select the Create new tag: YY.M.N on publish option that appears

    2. Verify that the new tag targets the main branch

    3. You can leave the release title blank, GitHub will default to the tag name

    4. Copy and paste the raw changelog Markdown for the current release into the description box

  5. Publish the GitHub Release, triggering release automation that will handle the rest

  6. 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.

Changelog template#

Use the following template for a clean changelog after the release:

## Unreleased

### Highlights

<!-- Include any especially major or disruptive changes here -->

### Stable style

<!-- Changes that affect Black's stable style -->

### Preview style

<!-- Changes that affect Black's preview style -->

### Configuration

<!-- Changes to how Black can be configured -->

### Packaging

<!-- Changes to how Black is packaged, such as dependency requirements -->

### Parser

<!-- Changes to the parser or to version autodetection -->

### Performance

<!-- Changes that improve Black's performance. -->

### Output

<!-- Changes to Black's terminal output and error messages -->

### _Blackd_

<!-- Changes to blackd -->

### Integrations

<!-- For example, Docker, GitHub Actions, pre-commit, editors -->

### Documentation

<!-- Major changes to documentation and policies. Small docs changes
     don't need a changelog entry. -->
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.

Developer reference#

Note

As of June 2023, the documentation of Black classes and Black exceptions has been updated to the latest available version.

The documentation of Black functions is quite outdated and has been neglected. Many functions worthy of inclusion aren’t documented. Contributions are appreciated!

Contents are subject to change.

Black classes#

Contents are subject to change.

Black Classes#
BracketTracker#
class black.brackets.BracketTracker(depth: int = 0, bracket_match: ~typing.Dict[~typing.Tuple[int, int], ~blib2to3.pytree.Leaf] = <factory>, delimiters: ~typing.Dict[int, int] = <factory>, previous: ~blib2to3.pytree.Leaf | None = None, _for_loop_depths: ~typing.List[int] = <factory>, _lambda_argument_depths: ~typing.List[int] = <factory>, invisible: ~typing.List[~blib2to3.pytree.Leaf] = <factory>)#

Keeps track of brackets on a line.

mark(leaf: Leaf) None#

Mark leaf with bracket-related metadata. Keep track of delimiters.

All leaves receive an int bracket_depth field that stores how deep within brackets a given leaf is. 0 means there are no enclosing brackets that started on this line.

If a leaf is itself a closing bracket and there is a matching opening bracket earlier, it receives an opening_bracket field with which it forms a pair. This is a one-directional link to avoid reference cycles. Closing bracket without opening happens on lines continued from previous breaks, e.g. ) -> “ReturnType”: as part of a funcdef where we place the return type annotation on its own line of the previous closing RPAR.

If a leaf is a delimiter (a token on which Black can split the line if needed) and it’s on depth 0, its id() is stored in the tracker’s delimiters field.

any_open_brackets() bool#

Return True if there is an yet unmatched open bracket on the line.

max_delimiter_priority(exclude: Iterable[int] = ()) int#

Return the highest priority of a delimiter found on the line.

Values are consistent with what is_split_*_delimiter() return. Raises ValueError on no delimiters.

delimiter_count_with_priority(priority: int = 0) int#

Return the number of delimiters with the given priority.

If no priority is passed, defaults to max priority on the line.

maybe_increment_for_loop_variable(leaf: Leaf) bool#

In a for loop, or comprehension, the variables are often unpacks.

To avoid splitting on the comma in this situation, increase the depth of tokens between for and in.

maybe_decrement_after_for_loop_variable(leaf: Leaf) bool#

See maybe_increment_for_loop_variable above for explanation.

maybe_increment_lambda_arguments(leaf: Leaf) bool#

In a lambda expression, there might be more than one argument.

To avoid splitting on the comma in this situation, increase the depth of tokens between lambda and :.

maybe_decrement_after_lambda_arguments(leaf: Leaf) bool#

See maybe_increment_lambda_arguments above for explanation.

get_open_lsqb() Leaf | None#

Return the most recent opening square bracket (if any).

Line#
class black.lines.Line(mode: ~black.mode.Mode, depth: int = 0, leaves: ~typing.List[~blib2to3.pytree.Leaf] = <factory>, comments: ~typing.Dict[int, ~typing.List[~blib2to3.pytree.Leaf]] = <factory>, bracket_tracker: ~black.brackets.BracketTracker = <factory>, inside_brackets: bool = False, should_split_rhs: bool = False, magic_trailing_comma: ~blib2to3.pytree.Leaf | None = None)#

Holds leaves and comments. Can be printed with str(line).

append(leaf: Leaf, preformatted: bool = False, track_bracket: bool = False) None#

Add a new leaf to the end of the line.

Unless preformatted is True, the leaf will receive a new consistent whitespace prefix and metadata applied by BracketTracker. Trailing commas are maybe removed, unpacked for loop variables are demoted from being delimiters.

Inline comments are put aside.

append_safe(leaf: Leaf, preformatted: bool = False) None#

Like append() but disallow invalid standalone comment structure.

Raises ValueError when any leaf is appended after a standalone comment or when a standalone comment is not the first leaf on the line.

property is_comment: bool#

Is this line a standalone comment?

property is_decorator: bool#

Is this line a decorator?

property is_import: bool#

Is this an import line?

property is_with_or_async_with_stmt: bool#

Is this a with_stmt line?

property is_class: bool#

Is this line a class definition?

property is_stub_class: bool#

Is this line a class definition with a body consisting only of “…”?

property is_def: bool#

Is this a function definition? (Also returns True for async defs.)

property is_stub_def: bool#

Is this line a function definition with a body consisting only of “…”?

property is_class_paren_empty: bool#

Is this a class with no base classes but using parentheses?

Those are unnecessary and should be removed.

property is_triple_quoted_string: bool#

Is the line a triple quoted string?

property opens_block: bool#

Does this line open a new level of indentation.

is_fmt_pass_converted(*, first_leaf_matches: Callable[[Leaf], bool] | None = None) bool#

Is this line converted from fmt off/skip code?

If first_leaf_matches is not None, it only returns True if the first leaf of converted code matches.

contains_standalone_comments(depth_limit: int = 9223372036854775807) bool#

If so, needs to be split before emitting.

has_magic_trailing_comma(closing: Leaf, ensure_removable: bool = False) bool#

Return True if we have a magic trailing comma, that is when: - there’s a trailing comma here - it’s not a one-tuple - it’s not a single-element subscript Additionally, if ensure_removable: - it’s not from square bracket indexing (specifically, single-element square bracket indexing)

append_comment(comment: Leaf) bool#

Add an inline or standalone comment to the line.

comments_after(leaf: Leaf) List[Leaf]#

Generate comments that should appear directly after leaf.

remove_trailing_comma() None#

Remove the trailing comma and moves the comments attached to it.

is_complex_subscript(leaf: Leaf) bool#

Return True iff leaf is part of a slice with non-trivial exprs.

enumerate_with_length(reversed: bool = False) Iterator[Tuple[int, Leaf, int]]#

Return an enumeration of leaves with their length.

Stops prematurely on multiline strings and standalone comments.

__str__() str#

Render the line.

__bool__() bool#

Return True if the line has leaves or comments.

RHSResult#
class black.lines.RHSResult(head: Line, body: Line, tail: Line, opening_bracket: Leaf, closing_bracket: Leaf)#

Intermediate split result from a right hand split.

LinesBlock#
class black.lines.LinesBlock(mode: ~black.mode.Mode, previous_block: ~black.lines.LinesBlock | None, original_line: ~black.lines.Line, before: int = 0, content_lines: ~typing.List[str] = <factory>, after: int = 0)#

Class that holds information about a block of formatted lines.

This is introduced so that the EmptyLineTracker can look behind the standalone comments and adjust their empty lines for class or def lines.

EmptyLineTracker#
class black.lines.EmptyLineTracker(mode: ~black.mode.Mode, previous_line: ~black.lines.Line | None = None, previous_block: ~black.lines.LinesBlock | None = None, previous_defs: ~typing.List[~black.lines.Line] = <factory>, semantic_leading_comment: ~black.lines.LinesBlock | None = None)#

Provides a stateful method that returns the number of potential extra empty lines needed before and after the currently processed line.

Note: this tracker works on lines that haven’t been split yet. It assumes the prefix of the first leaf consists of optional newlines. Those newlines are consumed by maybe_empty_lines() and included in the computation.

maybe_empty_lines(current_line: Line) LinesBlock#

Return the number of extra empty lines before and after the current_line.

This is for separating def, async def and class with extra empty lines (two on module-level).

LineGenerator#
class black.linegen.LineGenerator(mode: Mode, features: Collection[Feature])#

Bases: Visitor[Line]

Generates reformatted Line objects. Empty lines are not emitted.

Note: destroys the tree it’s visiting by mutating prefixes of its leaves in ways that will no longer stringify to valid Python code on the tree.

line(indent: int = 0) Iterator[Line]#

Generate a line.

If the line is empty, only emit if it makes sense. If the line is too long, split it first and then generate.

If any lines were generated, set up a new current_line.

visit_default(node: Leaf | Node) Iterator[Line]#

Default visit_*() implementation. Recurses to children of node.

visit_test(node: Node) Iterator[Line]#

Visit an x if y else z test

visit_INDENT(node: Leaf) Iterator[Line]#

Increase indentation level, maybe yield a line.

visit_DEDENT(node: Leaf) Iterator[Line]#

Decrease indentation level, maybe yield a line.

visit_stmt(node: Node, keywords: Set[str], parens: Set[str]) Iterator[Line]#

Visit a statement.

This implementation is shared for if, while, for, try, except, def, with, class, assert, and assignments.

The relevant Python language keywords for a given statement will be NAME leaves within it. This methods puts those on a separate line.

parens holds a set of string leaf values immediately after which invisible parens should be put.

visit_funcdef(node: Node) Iterator[Line]#

Visit function definition.

visit_match_case(node: Node) Iterator[Line]#

Visit either a match or case statement.

visit_suite(node: Node) Iterator[Line]#

Visit a suite.

visit_simple_stmt(node: Node) Iterator[Line]#

Visit a statement without nested statements.

visit_async_stmt(node: Node) Iterator[Line]#

Visit async def, async for, async with.

visit_decorators(node: Node) Iterator[Line]#

Visit decorators.

visit_SEMI(leaf: Leaf) Iterator[Line]#

Remove a semicolon and put the other statement on a separate line.

visit_ENDMARKER(leaf: Leaf) Iterator[Line]#

End of file. Process outstanding comments and end with a newline.

visit_factor(node: Node) Iterator[Line]#

Force parentheses between a unary op and a binary power:

-2 ** 8 -> -(2 ** 8)

ProtoComment#
class black.comments.ProtoComment(type: int, value: str, newlines: int, consumed: int)#

Describes a piece of syntax that is a comment.

It’s not a blib2to3.pytree.Leaf so that:

  • it can be cached (Leaf objects should not be reused more than once as they store their lineno, column, prefix, and parent information);

  • newlines and consumed fields are kept separate from the value. This simplifies handling of special marker comments like # fmt: off/on.

Mode#
class black.mode.Mode(target_versions: Set[black.mode.TargetVersion] = <factory>, line_length: int = 88, string_normalization: bool = True, is_pyi: bool = False, is_ipynb: bool = False, skip_source_first_line: bool = False, magic_trailing_comma: bool = True, experimental_string_processing: bool = False, python_cell_magics: Set[str] = <factory>, preview: bool = False)#
Report#
class black.report.Report(check: bool = False, diff: bool = False, quiet: bool = False, verbose: bool = False, change_count: int = 0, same_count: int = 0, failure_count: int = 0)#

Provides a reformatting counter. Can be rendered with str(report).

done(src: Path, changed: Changed) None#

Increment the counter for successful reformatting. Write out a message.

failed(src: Path, message: str) None#

Increment the counter for failed reformatting. Write out a message.

property return_code: int#

Return the exit code that the app should use.

This considers the current state of changed files and failures: - if there were any failures, return 123; - if any files were changed and –check is being used, return 1; - otherwise return 0.

__str__() str#

Render a color report of the current state.

Use click.unstyle to remove colors.

Ok#
class black.rusty.Ok(value: T)#

Bases: Generic[T]

Err#
class black.rusty.Err(e: E)#

Bases: Generic[E]

Visitor#
class black.nodes.Visitor#

Bases: Generic[T]

Basic lib2to3 visitor that yields things of type T on visit().

visit(node: Leaf | Node) Iterator[T]#

Main method to visit node and its children.

It tries to find a visit_*() method for the given node.type, like visit_simple_stmt for Node objects or visit_INDENT for Leaf objects. If no dedicated visit_*() method is found, chooses visit_default() instead.

Then yields objects of type T from the selected visitor.

visit_default(node: Leaf | Node) Iterator[T]#

Default visit_*() implementation. Recurses to children of node.

StringTransformer#
class black.trans.StringTransformer(line_length: int, normalize_strings: bool)#

Bases: ABC

An implementation of the Transformer protocol that relies on its subclasses overriding the template methods do_match(…) and do_transform(…).

This Transformer works exclusively on strings (for example, by merging or splitting them).

The following sections can be found among the docstrings of each concrete StringTransformer subclass.

Requirements:

Which requirements must be met of the given Line for this StringTransformer to be applied?

Transformations:

If the given Line meets all of the above requirements, which string transformations can you expect to be applied to it by this StringTransformer?

Collaborations:

What contractual agreements does this StringTransformer have with other StringTransfomers? Such collaborations should be eliminated/minimized as much as possible.

abstract do_match(line: Line) Ok[List[int]] | Err[CannotTransform]#
Returns:

  • Ok(string_indices) such that for each index, line.leaves[index] is our target string if a match was able to be made. For transformers that don’t result in more lines (e.g. StringMerger, StringParenStripper), multiple matches and transforms are done at once to reduce the complexity. OR

  • Err(CannotTransform), if no match could be made.

abstract do_transform(line: Line, string_indices: List[int]) Iterator[Ok[Line] | Err[CannotTransform]]#
Yields:
  • Ok(new_line) where new_line is the new transformed line. OR

  • Err(CannotTransform) if the transformation failed for some reason. The do_match(…) template method should usually be used to reject the form of the given Line, but in some cases it is difficult to know whether or not a Line meets the StringTransformer’s requirements until the transformation is already midway.

Side Effects:

This method should NOT mutate @line directly, but it MAY mutate the Line’s underlying Node structure. (WARNING: If the underlying Node structure IS altered, then this method should NOT be allowed to yield an CannotTransform after that point.)

CustomSplit#
class black.trans.CustomSplit(has_prefix: bool, break_idx: int)#

A custom (i.e. manual) string split.

A single CustomSplit instance represents a single substring.

Examples

Consider the following string: ` "Hi there friend." " This is a custom" f" string {split}." `

This string will correspond to the following three CustomSplit instances: ` CustomSplit(False, 16) CustomSplit(False, 17) CustomSplit(True, 16) `

CustomSplitMapMixin#
class black.trans.CustomSplitMapMixin#

Bases: object

This mixin class is used to map merged strings to a sequence of CustomSplits, which will then be used to re-split the strings iff none of the resultant substrings go over the configured max line length.

add_custom_splits(string: str, custom_splits: Iterable[CustomSplit]) None#

Custom Split Map Setter Method

Side Effects:

Adds a mapping from @string to the custom splits @custom_splits.

pop_custom_splits(string: str) List[CustomSplit]#

Custom Split Map Getter Method

Returns:

  • A list of the custom splits that are mapped to @string, if any exist. OR

  • [], otherwise.

Side Effects:

Deletes the mapping between @string and its associated custom splits (which are returned to the caller).

has_custom_splits(string: str) bool#
Returns:

True iff @string is associated with a set of custom splits.

StringMerger#
class black.trans.StringMerger(line_length: int, normalize_strings: bool)#

Bases: StringTransformer, CustomSplitMapMixin

StringTransformer that merges strings together.

Requirements:

(A) The line contains adjacent strings such that ALL of the validation checks listed in StringMerger._validate_msg(…)’s docstring pass. OR (B) The line contains a string which uses line continuation backslashes.

Transformations:

Depending on which of the two requirements above where met, either:

(A) The string group associated with the target string is merged. OR (B) All line-continuation backslashes are removed from the target string.

Collaborations:

StringMerger provides custom split information to StringSplitter.

do_match(line: Line) Ok[List[int]] | Err[CannotTransform]#
Returns:

  • Ok(string_indices) such that for each index, line.leaves[index] is our target string if a match was able to be made. For transformers that don’t result in more lines (e.g. StringMerger, StringParenStripper), multiple matches and transforms are done at once to reduce the complexity. OR

  • Err(CannotTransform), if no match could be made.

do_transform(line: Line, string_indices: List[int]) Iterator[Ok[Line] | Err[CannotTransform]]#
Yields:
  • Ok(new_line) where new_line is the new transformed line. OR

  • Err(CannotTransform) if the transformation failed for some reason. The do_match(…) template method should usually be used to reject the form of the given Line, but in some cases it is difficult to know whether or not a Line meets the StringTransformer’s requirements until the transformation is already midway.

Side Effects:

This method should NOT mutate @line directly, but it MAY mutate the Line’s underlying Node structure. (WARNING: If the underlying Node structure IS altered, then this method should NOT be allowed to yield an CannotTransform after that point.)

StringParenStripper#
class black.trans.StringParenStripper(line_length: int, normalize_strings: bool)#

Bases: StringTransformer

StringTransformer that strips surrounding parentheses from strings.

Requirements:
The line contains a string which is surrounded by parentheses and:
  • The target string is NOT the only argument to a function call.

  • The target string is NOT a “pointless” string.

  • If the target string contains a PERCENT, the brackets are not preceded or followed by an operator with higher precedence than PERCENT.

Transformations:

The parentheses mentioned in the ‘Requirements’ section are stripped.

Collaborations:

StringParenStripper has its own inherent usefulness, but it is also relied on to clean up the parentheses created by StringParenWrapper (in the event that they are no longer needed).

do_match(line: Line) Ok[List[int]] | Err[CannotTransform]#
Returns:

  • Ok(string_indices) such that for each index, line.leaves[index] is our target string if a match was able to be made. For transformers that don’t result in more lines (e.g. StringMerger, StringParenStripper), multiple matches and transforms are done at once to reduce the complexity. OR

  • Err(CannotTransform), if no match could be made.

do_transform(line: Line, string_indices: List[int]) Iterator[Ok[Line] | Err[CannotTransform]]#
Yields:
  • Ok(new_line) where new_line is the new transformed line. OR

  • Err(CannotTransform) if the transformation failed for some reason. The do_match(…) template method should usually be used to reject the form of the given Line, but in some cases it is difficult to know whether or not a Line meets the StringTransformer’s requirements until the transformation is already midway.

Side Effects:

This method should NOT mutate @line directly, but it MAY mutate the Line’s underlying Node structure. (WARNING: If the underlying Node structure IS altered, then this method should NOT be allowed to yield an CannotTransform after that point.)

BaseStringSplitter#
class black.trans.BaseStringSplitter(line_length: int, normalize_strings: bool)#

Bases: StringTransformer

Abstract class for StringTransformers which transform a Line’s strings by splitting them or placing them on their own lines where necessary to avoid going over the configured line length.

Requirements:
  • The target string value is responsible for the line going over the line length limit. It follows that after all of black’s other line split methods have been exhausted, this line (or one of the resulting lines after all line splits are performed) would still be over the line_length limit unless we split this string. AND

  • The target string is NOT a “pointless” string (i.e. a string that has no parent or siblings). AND

  • The target string is not followed by an inline comment that appears to be a pragma. AND

  • The target string is not a multiline (i.e. triple-quote) string.

abstract do_splitter_match(line: Line) Ok[List[int]] | Err[CannotTransform]#

BaseStringSplitter asks its clients to override this method instead of StringTransformer.do_match(…).

Follows the same protocol as StringTransformer.do_match(…).

Refer to help(StringTransformer.do_match) for more information.

do_match(line: Line) Ok[List[int]] | Err[CannotTransform]#
Returns:

  • Ok(string_indices) such that for each index, line.leaves[index] is our target string if a match was able to be made. For transformers that don’t result in more lines (e.g. StringMerger, StringParenStripper), multiple matches and transforms are done at once to reduce the complexity. OR

  • Err(CannotTransform), if no match could be made.

StringSplitter#
class black.trans.StringSplitter(line_length: int, normalize_strings: bool)#

Bases: BaseStringSplitter, CustomSplitMapMixin

StringTransformer that splits “atom” strings (i.e. strings which exist on lines by themselves).

Requirements:
  • The line consists ONLY of a single string (possibly prefixed by a string operator [e.g. ‘+’ or ‘==’]), MAYBE a string trailer, and MAYBE a trailing comma. AND

  • All of the requirements listed in BaseStringSplitter’s docstring.

Transformations:

The string mentioned in the ‘Requirements’ section is split into as many substrings as necessary to adhere to the configured line length.

In the final set of substrings, no substring should be smaller than MIN_SUBSTR_SIZE characters.

The string will ONLY be split on spaces (i.e. each new substring should start with a space). Note that the string will NOT be split on a space which is escaped with a backslash.

If the string is an f-string, it will NOT be split in the middle of an f-expression (e.g. in f”FooBar: {foo() if x else bar()}”, {foo() if x else bar()} is an f-expression).

If the string that is being split has an associated set of custom split records and those custom splits will NOT result in any line going over the configured line length, those custom splits are used. Otherwise the string is split as late as possible (from left-to-right) while still adhering to the transformation rules listed above.

Collaborations:

StringSplitter relies on StringMerger to construct the appropriate CustomSplit objects and add them to the custom split map.

do_splitter_match(line: Line) Ok[List[int]] | Err[CannotTransform]#

BaseStringSplitter asks its clients to override this method instead of StringTransformer.do_match(…).

Follows the same protocol as StringTransformer.do_match(…).

Refer to help(StringTransformer.do_match) for more information.

do_transform(line: Line, string_indices: List[int]) Iterator[Ok[Line] | Err[CannotTransform]]#
Yields:
  • Ok(new_line) where new_line is the new transformed line. OR

  • Err(CannotTransform) if the transformation failed for some reason. The do_match(…) template method should usually be used to reject the form of the given Line, but in some cases it is difficult to know whether or not a Line meets the StringTransformer’s requirements until the transformation is already midway.

Side Effects:

This method should NOT mutate @line directly, but it MAY mutate the Line’s underlying Node structure. (WARNING: If the underlying Node structure IS altered, then this method should NOT be allowed to yield an CannotTransform after that point.)

StringParenWrapper#
class black.trans.StringParenWrapper(line_length: int, normalize_strings: bool)#

Bases: BaseStringSplitter, CustomSplitMapMixin

StringTransformer that wraps strings in parens and then splits at the LPAR.

Requirements:

All of the requirements listed in BaseStringSplitter’s docstring in addition to the requirements listed below:

  • The line is a return/yield statement, which returns/yields a string. OR

  • The line is part of a ternary expression (e.g. x = y if cond else z) such that the line starts with else <string>, where <string> is some string. OR

  • The line is an assert statement, which ends with a string. OR

  • The line is an assignment statement (e.g. x = <string> or x += <string>) such that the variable is being assigned the value of some string. OR

  • The line is a dictionary key assignment where some valid key is being assigned the value of some string. OR

  • The line is an lambda expression and the value is a string. OR

  • The line starts with an “atom” string that prefers to be wrapped in parens. It’s preferred to be wrapped when it’s is an immediate child of a list/set/tuple literal, AND the string is surrounded by commas (or is the first/last child).

Transformations:

The chosen string is wrapped in parentheses and then split at the LPAR.

We then have one line which ends with an LPAR and another line that starts with the chosen string. The latter line is then split again at the RPAR. This results in the RPAR (and possibly a trailing comma) being placed on its own line.

NOTE: If any leaves exist to the right of the chosen string (except for a trailing comma, which would be placed after the RPAR), those leaves are placed inside the parentheses. In effect, the chosen string is not necessarily being “wrapped” by parentheses. We can, however, count on the LPAR being placed directly before the chosen string.

In other words, StringParenWrapper creates “atom” strings. These can then be split again by StringSplitter, if necessary.

Collaborations:

In the event that a string line split by StringParenWrapper is changed such that it no longer needs to be given its own line, StringParenWrapper relies on StringParenStripper to clean up the parentheses it created.

For “atom” strings that prefers to be wrapped in parens, it requires StringSplitter to hold the split until the string is wrapped in parens.

do_splitter_match(line: Line) Ok[List[int]] | Err[CannotTransform]#

BaseStringSplitter asks its clients to override this method instead of StringTransformer.do_match(…).

Follows the same protocol as StringTransformer.do_match(…).

Refer to help(StringTransformer.do_match) for more information.

do_transform(line: Line, string_indices: List[int]) Iterator[Ok[Line] | Err[CannotTransform]]#
Yields:
  • Ok(new_line) where new_line is the new transformed line. OR

  • Err(CannotTransform) if the transformation failed for some reason. The do_match(…) template method should usually be used to reject the form of the given Line, but in some cases it is difficult to know whether or not a Line meets the StringTransformer’s requirements until the transformation is already midway.

Side Effects:

This method should NOT mutate @line directly, but it MAY mutate the Line’s underlying Node structure. (WARNING: If the underlying Node structure IS altered, then this method should NOT be allowed to yield an CannotTransform after that point.)

StringParser#
class black.trans.StringParser#

A state machine that aids in parsing a string’s “trailer”, which can be either non-existent, an old-style formatting sequence (e.g. % varX or % (varX, varY)), or a method-call / attribute access (e.g. .format(varX, varY)).

NOTE: A new StringParser object MUST be instantiated for each string trailer we need to parse.

Examples

We shall assume that line equals the Line object that corresponds to the following line of python code: ` x = "Some {}.".format("String") + some_other_string `

Furthermore, we will assume that string_idx is some index such that: ` assert line.leaves[string_idx].value == "Some {}." `

The following code snippet then holds: ` string_parser = StringParser() idx = string_parser.parse(line.leaves, string_idx) assert line.leaves[idx].type == token.PLUS `

parse(leaves: List[Leaf], string_idx: int) int#
Pre-conditions:
  • @leaves[@string_idx].type == token.STRING

Returns:

The index directly after the last leaf which is apart of the string trailer, if a “trailer” exists. OR @string_idx + 1, if no string “trailer” exists.

DebugVisitor#
class black.debug.DebugVisitor(tree_depth: int = 0)#

Bases: Visitor[T]

visit_default(node: Leaf | Node) Iterator[T]#

Default visit_*() implementation. Recurses to children of node.

classmethod show(code: str | Leaf | Node) None#

Pretty-print the lib2to3 AST of a given string of code.

Convenience method for debugging.

Replacement#
class black.handle_ipynb_magics.Replacement(mask: str, src: str)#
CellMagic#
class black.handle_ipynb_magics.CellMagic(name: str, params: str | None, body: str)#
CellMagicFinder#
class black.handle_ipynb_magics.CellMagicFinder(cell_magic: CellMagic | None = None)#

Bases: NodeVisitor

Find cell magics.

Note that the source of the abstract syntax tree will already have been processed by IPython’s TransformerManager().transform_cell.

For example,

%%time

foo()

would have been transformed to

get_ipython().run_cell_magic(‘time’, ‘’, ‘foo()n’)

and we look for instances of the latter.

visit_Expr(node: Expr) None#

Find cell magic, extract header and body.

OffsetAndMagic#
class black.handle_ipynb_magics.OffsetAndMagic(col_offset: int, magic: str)#
MagicFinder#
class black.handle_ipynb_magics.MagicFinder#

Bases: NodeVisitor

Visit cell to look for get_ipython calls.

Note that the source of the abstract syntax tree will already have been processed by IPython’s TransformerManager().transform_cell.

For example,

%matplotlib inline

would have been transformed to

get_ipython().run_line_magic(‘matplotlib’, ‘inline’)

and we look for instances of the latter (and likewise for other types of magics).

visit_Assign(node: Assign) None#

Look for system assign magics.

For example,

black_version = !black –version env = %env var

would have been (respectively) transformed to

black_version = get_ipython().getoutput(‘black –version’) env = get_ipython().run_line_magic(‘env’, ‘var’)

and we look for instances of any of the latter.

visit_Expr(node: Expr) None#

Look for magics in body of cell.

For examples,

!ls !!ls ?ls ??ls

would (respectively) get transformed to

get_ipython().system(‘ls’) get_ipython().getoutput(‘ls’) get_ipython().run_line_magic(‘pinfo’, ‘ls’) get_ipython().run_line_magic(‘pinfo2’, ‘ls’)

and we look for instances of any of the latter.

Cache#
class black.cache.Cache(mode: black.mode.Mode, cache_file: pathlib.Path, file_data: Dict[str, black.cache.FileData] = <factory>)#

Bases: object

classmethod read(mode: Mode) Self#

Read the cache if it exists and is well formed.

If it is not well formed, the call to write later should resolve the issue.

static hash_digest(path: Path) str#

Return hash digest for path.

static get_file_data(path: Path) FileData#

Return file data for path.

is_changed(source: Path) bool#

Check if source has changed compared to cached version.

filtered_cached(sources: Iterable[Path]) Tuple[Set[Path], Set[Path]]#

Split an iterable of paths in sources into two sets.

The first contains paths of files that modified on disk or are not in the cache. The other contains paths to non-modified files.

write(sources: Iterable[Path]) None#

Update the cache file data and write a new cache file.

Enum Classes#

Classes inherited from Python Enum class.

Changed#
class black.report.Changed(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)#

Bases: Enum

WriteBack#
class black.WriteBack(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)#

Bases: Enum

TargetVersion#
class black.mode.TargetVersion(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)#

Bases: Enum

Feature#
class black.mode.Feature(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)#

Bases: Enum

Preview#
class black.mode.Preview(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)#

Bases: Enum

Individual preview style features.

Black functions#

Contents are subject to change.

Assertions and checks#
black.assert_equivalent(src: str, dst: str) None#

Raise AssertionError if src and dst aren’t equivalent.

black.assert_stable(src: str, dst: str, mode: Mode) None#

Raise AssertionError if dst reformats differently the second time.

black.lines.can_be_split(line: Line) bool#

Return False if the line cannot be split for sure.

This is not an exhaustive search but a cheap heuristic that we can use to avoid some unfortunate formattings (mostly around wrapping unsplittable code in unnecessary parentheses).

black.lines.can_omit_invisible_parens(rhs: RHSResult, line_length: int) bool#

Does rhs.body have a shape safe to reformat without optional parens around it?

Returns True for only a subset of potentially nice looking formattings but the point is to not return false positives that end up producing lines that are too long.

black.nodes.is_empty_tuple(node: Leaf | Node) bool#

Return True if node holds an empty tuple.

black.nodes.is_import(leaf: Leaf) bool#

Return True if the given leaf starts an import statement.

black.lines.is_line_short_enough(line: Line, *, mode: Mode, line_str: str = '') bool#

For non-multiline strings, return True if line is no longer than line_length. For multiline strings, looks at the context around line to determine if it should be inlined or split up. Uses the provided line_str rendering, if any, otherwise computes a new one.

black.nodes.is_multiline_string(leaf: Leaf) bool#

Return True if leaf is a multiline string that actually spans many lines.

black.nodes.is_one_tuple(node: Leaf | Node) bool#

Return True if node holds a tuple with one element, with or without parens.

black.brackets.is_split_after_delimiter(leaf: Leaf, previous: Leaf | None = None) int#

Return the priority of the leaf delimiter, given a line break after it.

The delimiter priorities returned here are from those delimiters that would cause a line break after themselves.

Higher numbers are higher priority.

black.brackets.is_split_before_delimiter(leaf: Leaf, previous: Leaf | None = None) int#

Return the priority of the leaf delimiter, given a line break before it.

The delimiter priorities returned here are from those delimiters that would cause a line break before themselves.

Higher numbers are higher priority.

black.nodes.is_stub_body(node: Leaf | Node) bool#

Return True if node is a simple statement containing an ellipsis.

black.nodes.is_stub_suite(node: Node) bool#

Return True if node is a suite with a stub body.

black.nodes.is_vararg(leaf: Leaf, within: Set[int]) bool#

Return True if leaf is a star or double star in a vararg or kwarg.

If within includes VARARGS_PARENTS, this applies to function signatures. If within includes UNPACKING_PARENTS, it applies to right hand-side extended iterable unpacking (PEP 3132) and additional unpacking generalizations (PEP 448).

black.nodes.is_yield(node: Leaf | Node) bool#

Return True if node holds a yield or yield from expression.

Formatting#
black.format_file_contents(src_contents: str, *, fast: bool, mode: Mode) str#

Reformat contents of a file and return new contents.

If fast is False, additionally confirm that the reformatted code is valid by calling assert_equivalent() and assert_stable() on it. mode is passed to format_str().

black.format_file_in_place(src: Path, fast: bool, mode: Mode, write_back: WriteBack = WriteBack.NO, lock: Any = None) bool#

Format file under src path. Return True if changed.

If write_back is DIFF, write a diff to stdout. If it is YES, write reformatted code to the file. mode and fast options are passed to format_file_contents().

black.format_stdin_to_stdout(fast: bool, *, content: str | None = None, write_back: WriteBack = WriteBack.NO, mode: Mode) bool#

Format file on stdin. Return True if changed.

If content is None, it’s read from sys.stdin.

If write_back is YES, write reformatted code back to stdout. If it is DIFF, write a diff to stdout. The mode argument is passed to format_file_contents().

black.format_str(src_contents: str, *, mode: Mode) str#

Reformat a string and return new contents.

mode determines formatting options, such as how many characters per line are allowed. Example:

>>> import black
>>> print(black.format_str("def f(arg:str='')->None:...", mode=black.Mode()))
def f(arg: str = "") -> None:
    ...

A more complex example:

>>> print(
...   black.format_str(
...     "def f(arg:str='')->None: hey",
...     mode=black.Mode(
...       target_versions={black.TargetVersion.PY36},
...       line_length=10,
...       string_normalization=False,
...       is_pyi=False,
...     ),
...   ),
... )
def f(
    arg: str = '',
) -> None:
    hey
black.reformat_one(src: Path, fast: bool, write_back: WriteBack, mode: Mode, report: Report) None#

Reformat a single file under src without spawning child processes.

fast, write_back, and mode options are passed to format_file_in_place() or format_stdin_to_stdout().

async black.concurrency.schedule_formatting(sources: Set[Path], fast: bool, write_back: WriteBack, mode: Mode, report: Report, loop: AbstractEventLoop, executor: Executor) None#

Run formatting of sources in parallel using the provided executor.

(Use ProcessPoolExecutors for actual parallelism.)

write_back, fast, and mode options are passed to format_file_in_place().

File operations#
black.dump_to_file(*output: str, ensure_final_newline: bool = True) str#

Dump output to a temporary file. Return path to the file.

black.find_project_root(srcs: Sequence[str], stdin_filename: str | None = None) Tuple[Path, str]#

Return a directory containing .git, .hg, or pyproject.toml.

That directory will be a common parent of all files and directories passed in srcs.

If no directory in the tree contains a marker that would specify it’s the project root, the root of the file system is returned.

Returns a two-tuple with the first element as the project root path and the second element as a string describing the method by which the project root was discovered.

black.gen_python_files(paths: Iterable[Path], root: Path, include: Pattern[str], exclude: Pattern[str], extend_exclude: Pattern[str] | None, force_exclude: Pattern[str] | None, report: Report, gitignore_dict: Dict[Path, PathSpec] | None, *, verbose: bool, quiet: bool) Iterator[Path]#

Generate all files under path whose paths are not excluded by the exclude_regex, extend_exclude, or force_exclude regexes, but are included by the include regex.

Symbolic links pointing outside of the root directory are ignored.

report is where output about exclusions goes.

black.read_pyproject_toml(ctx: Context, param: Parameter, value: str | None) str | None#

Inject Black configuration from “pyproject.toml” into defaults in ctx.

Returns the path to a successfully found and read configuration file, None otherwise.

Parsing#
black.decode_bytes(src: bytes) Tuple[str, str, str]#

Return a tuple of (decoded_contents, encoding, newline).

newline is either CRLF or LF but decoded_contents is decoded with universal newlines (i.e. only contains LF).

black.parsing.lib2to3_parse(src_txt: str, target_versions: Iterable[TargetVersion] = ()) Node#

Given a string with source, return the lib2to3 Node.

black.parsing.lib2to3_unparse(node: Node) str#

Given a lib2to3 node, return its string representation.

Split functions#
black.linegen.bracket_split_build_line(leaves: List[Leaf], original: Line, opening_bracket: Leaf, *, component: _BracketSplitComponent) Line#

Return a new line with given leaves and respective comments from original.

If it’s the head component, brackets will be tracked so trailing commas are respected.

If it’s the body component, the result line is one-indented inside brackets and as such has its first leaf’s prefix normalized and a trailing comma added when expected.

black.linegen.bracket_split_succeeded_or_raise(head: Line, body: Line, tail: Line) None#

Raise CannotSplit if the last left- or right-hand split failed.

Do nothing otherwise.

A left- or right-hand split is based on a pair of brackets. Content before (and including) the opening bracket is left on one line, content inside the brackets is put on a separate line, and finally content starting with and following the closing bracket is put on a separate line.

Those are called head, body, and tail, respectively. If the split produced the same line (all content in head) or ended up with an empty body and the tail is just the closing bracket, then it’s considered failed.

black.linegen.delimiter_split(line: Line, features: Collection[Feature], mode: Mode) Iterator[Line]#

Split according to delimiters of the highest priority.

If the appropriate Features are given, the split will add trailing commas also in function signatures and calls that contain * and **.

black.linegen.left_hand_split(line: Line, _features: Collection[Feature], mode: Mode) Iterator[Line]#

Split line into many lines, starting with the first matching bracket pair.

Note: this usually looks weird, only use this for function definitions. Prefer RHS otherwise. This is why this function is not symmetrical with right_hand_split() which also handles optional parentheses.

black.linegen.right_hand_split(line: Line, mode: Mode, features: Collection[Feature] = (), omit: Collection[int] = ()) Iterator[Line]#

Split line into many lines, starting with the last matching bracket pair.

If the split was by optional parentheses, attempt splitting without them, too. omit is a collection of closing bracket IDs that shouldn’t be considered for this split.

Note: running this function modifies bracket_depth on the leaves of line.

black.linegen.standalone_comment_split(line: Line, features: Collection[Feature], mode: Mode) Iterator[Line]#

Split standalone comments from the rest of the line.

black.linegen.transform_line(line: Line, mode: Mode, features: Collection[Feature] = ()) Iterator[Line]#

Transform a line, potentially splitting it into many lines.

They should fit in the allotted line_length but might not be able to.

features are syntactical features that may be used in the output.

Caching#
black.cache.get_cache_dir() Path#

Get the cache directory used by black.

Users can customize this directory on all systems using BLACK_CACHE_DIR environment variable. By default, the cache directory is the user cache directory under the black application.

This result is immediately set to a constant black.cache.CACHE_DIR as to avoid repeated calls.

black.cache.get_cache_file(mode: Mode) Path#
Utilities#
black.debug.DebugVisitor.show(code: str) None#

Pretty-print the lib2to3 AST of a given string of code.

black.concurrency.cancel(tasks: Iterable[Task[Any]]) None#

asyncio signal handler that cancels all tasks and reports to stderr.

black.nodes.child_towards(ancestor: Node, descendant: Leaf | Node) Leaf | Node | None#

Return the child of ancestor that contains descendant.

black.nodes.container_of(leaf: Leaf) Leaf | Node#

Return leaf or one of its ancestors that is the topmost container of it.

By “container” we mean a node where leaf is the very first child.

black.comments.convert_one_fmt_off_pair(node: Node) bool#

Convert content of a single # fmt: off/# fmt: on into a standalone comment.

Returns True if a pair was converted.

black.diff(a: str, b: str, a_name: str, b_name: str) str#

Return a unified diff string between strings a and b.

black.linegen.dont_increase_indentation(split_func: Callable[[Line, Collection[Feature], Mode], Iterator[Line]]) Callable[[Line, Collection[Feature], Mode], Iterator[Line]]#

Normalize prefix of the first leaf in every line returned by split_func.

This is a decorator over relevant split functions.

black.numerics.format_float_or_int_string(text: str) str#

Formats a float string like “1.0”.

black.nodes.ensure_visible(leaf: Leaf) None#

Make sure parentheses are visible.

They could be invisible as part of some statements (see normalize_invisible_parens() and visit_import_from()).

black.lines.enumerate_reversed(sequence: Sequence[T]) Iterator[Tuple[int, T]]#

Like reversed(enumerate(sequence)) if that were possible.

black.comments.generate_comments(leaf: Leaf | Node) Iterator[Leaf]#

Clean the prefix of the leaf and generate comments from it, if any.

Comments in lib2to3 are shoved into the whitespace prefix. This happens in pgen2/driver.py:Driver.parse_tokens(). This was a brilliant implementation move because it does away with modifying the grammar to include all the possible places in which comments can be placed.

The sad consequence for us though is that comments don’t “belong” anywhere. This is why this function generates simple parentless Leaf objects for comments. We simply don’t know what the correct parent should be.

No matter though, we can live without this. We really only need to differentiate between inline and standalone comments. The latter don’t share the line with any code.

Inline comments are emitted as regular token.COMMENT leaves. Standalone are emitted with a fake STANDALONE_COMMENT token identifier.

black.comments.generate_ignored_nodes(leaf: Leaf, comment: ProtoComment) Iterator[Leaf | Node]#

Starting from the container of leaf, generate all leaves until # fmt: on.

If comment is skip, returns leaf only. Stops at the end of the block.

black.comments.is_fmt_on(container: Leaf | Node) bool#

Determine whether formatting is switched on within a container. Determined by whether the last # fmt: comment is on or off.

black.comments.children_contains_fmt_on(container: Leaf | Node) bool#

Determine if children have formatting switched on.

black.nodes.first_leaf_of(node: Leaf | Node) Leaf | None#

Returns the first leaf of the node tree.

black.linegen.generate_trailers_to_omit(line: Line, line_length: int) Iterator[Set[int]]#

Generate sets of closing bracket IDs that should be omitted in a RHS.

Brackets can be omitted if the entire trailer up to and including a preceding closing bracket fits in one line.

Yielded sets are cumulative (contain results of previous yields, too). First set is empty, unless the line should explode, in which case bracket pairs until the one that needs to explode are omitted.

black.get_future_imports(node: Node) Set[str]#

Return a set of __future__ imports in the file.

black.comments.list_comments(prefix: str, *, is_endmarker: bool) List[ProtoComment]#

Return a list of ProtoComment objects parsed from the given prefix.

black.comments.make_comment(content: str) str#

Return a consistently formatted comment from the given content string.

All comments (except for “##”, “#!”, “#:”, ‘#’”) should have a single space between the hash sign and the content.

If content didn’t start with a hash sign, one is provided.

black.linegen.maybe_make_parens_invisible_in_atom(node: Leaf | Node, parent: Leaf | Node, remove_brackets_around_comma: bool = False) bool#

If it’s safe, make the parens in the atom node invisible, recursively. Additionally, remove repeated, adjacent invisible parens from the atom node as they are redundant.

Returns whether the node should itself be wrapped in invisible parentheses.

black.brackets.max_delimiter_priority_in_atom(node: Leaf | Node) int#

Return maximum delimiter priority inside node.

This is specific to atoms with contents contained in a pair of parentheses. If node isn’t an atom or there are no enclosing parentheses, returns 0.

black.normalize_fmt_off(node: Node) None#

Convert content between # fmt: off/# fmt: on into standalone comments.

black.numerics.normalize_numeric_literal(leaf: Leaf) None#

Normalizes numeric (float, int, and complex) literals.

All letters used in the representation are normalized to lowercase.

black.linegen.normalize_prefix(leaf: Leaf, *, inside_brackets: bool) None#

Leave existing extra newlines if not inside_brackets. Remove everything else.

Note: don’t use backslashes for formatting or you’ll lose your voting rights.

black.strings.normalize_string_prefix(s: str) str#

Make all string prefixes lowercase.

black.strings.normalize_string_quotes(s: str) str#

Prefer double quotes but only if it doesn’t cause more escaping.

Adds or removes backslashes as appropriate. Doesn’t parse and fix strings nested in f-strings.

black.linegen.normalize_invisible_parens(node: Node, parens_after: Set[str], *, mode: Mode, features: Collection[Feature]) None#

Make existing optional parentheses invisible or create new ones.

parens_after is a set of string leaf values immediately after which parens should be put.

Standardizes on visible parentheses for single-element tuples, and keeps existing visible parentheses for other tuples and generator expressions.

black.nodes.preceding_leaf(node: Leaf | Node | None) Leaf | None#

Return the first leaf that precedes node, if any.

black.re_compile_maybe_verbose(regex: str) Pattern[str]#

Compile a regular expression string in regex.

If it contains newlines, use verbose mode.

black.linegen.should_split_line(line: Line, opening_bracket: Leaf) bool#

Should line be immediately split with delimiter_split() after RHS?

black.concurrency.shutdown(loop: AbstractEventLoop) None#

Cancel all pending tasks on loop, wait for them, and close the loop.

black.strings.sub_twice(regex: Pattern[str], replacement: str, original: str) str#

Replace regex with replacement twice on original.

This is used by string normalization to perform replaces on overlapping matches.

black.nodes.whitespace(leaf: Leaf, *, complex_subscript: bool, mode: Mode) str#

Return whitespace prefix if needed for the given leaf.

complex_subscript signals whether the given leaf is part of a subscription which has non-trivial arguments, like arithmetic expressions or function calls.

Black exceptions#

Contents are subject to change.

exception black.trans.CannotTransform#

Base class for errors raised by Transformers.

exception black.linegen.CannotSplit#

A readable split that fits the allotted line length is impossible.

exception black.brackets.BracketMatchError#

Raised when an opening bracket is unable to be matched to a closing bracket.

exception black.report.NothingChanged#

Raised when reformatted code is the same as source.

exception black.parsing.InvalidInput#

Raised when input source code fails all parse attempts.

exception black.mode.Deprecated#

Visible deprecation warning.

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.

If you need a reference of the functions, classes, etc. available to you while developing Black, there’s the Developer reference docs.

Change Log#

Unreleased#

Highlights#
Stable style#
Preview style#
Configuration#
Packaging#
  • Upgrade to mypy 1.5.1 (#3864)

Parser#
Performance#
Output#
Blackd#
Integrations#
Documentation#

23.9.0#

Preview style#
  • More concise formatting for dummy implementations (#3796)

  • In stub files, add a blank line between a statement with a body (e.g an if sys.version_info > (3, x):) and a function definition on the same level (#3862)

  • Fix a bug whereby spaces were removed from walrus operators within subscript(#3823)

Configuration#
  • Black now applies exclusion and ignore logic before resolving symlinks (#3846)

Performance#
  • Avoid importing IPython if notebook cells do not contain magics (#3782)

  • Improve caching by comparing file hashes as fallback for mtime and size (#3821)

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 to https://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 by ENV_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#
  • Implicitly concatenated strings used as function args are no longer wrapped inside parentheses (#3640)

  • Remove blank lines between a class definition and its docstring (#3692)

Configuration#
  • The --workers argument to Black can now be specified via the BLACK_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 the pyproject.toml found isn’t in the current working directory (#3719)

  • Black will now error if exclude and extend-exclude have invalid data types in pyproject.toml, instead of silently doing the wrong thing (#3764)

Packaging#
  • Upgrade mypyc from 0.991 to 1.3 (#3697)

  • Remove patching of Click that mitigated errors on Python 3.6 with LANG=C (#3768)

Parser#
  • Add support for the new PEP 695 syntax in Python 3.12 (#3703)

Performance#
  • Speed up Black significantly when the cache is full (#3751)

  • Avoid importing IPython in a case where we wouldn’t need it (#3748)

Output#
  • Use aware UTC datetimes internally, avoids deprecation warning on Python 3.12 (#3728)

  • Change verbose logging to exactly mirror Black’s logic for source discovery (#3749)

Blackd#
  • The blackd argument parser now shows the default values for options in their help text (#3712)

Integrations#
Documentation#
  • Add a CITATION.cff file to the root of the repository, containing metadata on how to cite this software (#3723)

  • Update the classes and exceptions documentation in Developer reference to match the latest code base (#3755)

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, and async 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#
  • Update GitHub Action to use the version of Black equivalent to action’s version if version input is not specified (#3543)

  • Fix missing Python binary path in autoload script for vim (#3508)

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 in pyproject.toml (#3219)

Packaging#
  • Upgrade mypyc from 0.971 to 0.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 version 22.0 or later. This is required for new functionality that needs to parse part of the project metadata (#3219)

Output#
  • Calling black --help multiple times will return the same help contents each time (#3516)

  • Verbose logging now shows the values of pyproject.toml configuration variables (#3392)

  • Fix false symlink detection messages in verbose output due to using an incorrect relative path to the project root (#3385)

Integrations#
  • Move 3.11 CI to normal flow now that all dependencies support 3.11 (#3446)

  • Docker: Add new latest_prerelease tag automation to follow latest black alpha release on docker images (#3465)

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#
  • Fix incorrectly applied .gitignore rules by considering the .gitignore location and the relative path to the target file (#3338)

  • Fix incorrectly ignoring .gitignore presence when more than one source directory is specified (#3336)

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#
  • .ipynb_checkpoints directories are now excluded by default (#3293)

  • Add --skip-source-first-line / -x option to ignore the first line of source code while formatting (#3299)

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#
  • Vim plugin: add flag (g:black_preview) to enable/disable the preview style (#3246)

  • Update GitHub Action to support formatting of Jupyter Notebook files via a jupyter option (#3282)

  • Update GitHub Action to support use of version specifiers (e.g. <23) for Black version (#3265)

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#
  • Fix an infinite loop when using # fmt: on/off in the middle of an expression or code block (#3158)

  • Fix incorrect handling of # fmt: skip on colon (:) lines (#3148)

  • Comments are no longer deleted when a line had spaces removed around power operators (#2874)

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 the X-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#
  • Vim plugin: prefix messages with Black: so it’s clear they come from Black (#3194)

  • Docker: changed to a /opt/venv installation + added to PATH to be available to non-root users (#3202)

Output#
  • Change from deprecated asyncio.get_event_loop() to create our event loop which removes DeprecationWarning (#3164)

  • Remove logging from internal blib2to3 library since it regularly emits error logs about failed caching that can and should be ignored (#3193)

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 of tomllib on Python 3.11 builds where tomllib is not available (#2987)

Parser#
  • PEP 654 syntax (for example, except *ExceptionGroup:) is now supported (#3016)

  • PEP 646 syntax (for example, Array[Batch, *Shape] or def fn(*args: *T) -> None) is now supported (#3071)

Vim Plugin#
  • Fix strtobool function. It didn’t parse true/on/false/off. (#3025)

22.3.0#

Preview style#
  • Code cell separators #%% are now standardised to # %% (#2919)

  • Remove unnecessary parentheses from except statements (#2939)

  • Remove unnecessary parentheses from tuple unpacking in for loops (#2945)

  • Avoid magic-trailing-comma in single-element subscripts (#2942)

Configuration#
  • Do not format __pypackages__ directories by default (#2836)

  • Add support for specifying stable version with --required-version (#2832).

  • Avoid crashing when the user has no homedir (#2814)

  • Avoid crashing when md5 is not available (#2905)

  • Fix handling of directory junctions on Windows (#2904)

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 of tomli (#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 and async for statements, e.g for 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#
  • Remove Python 2 support (#2740)

  • Introduce the --preview flag (#2752)

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 and yield 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() or case() 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#
  • Speed-up the new backtracking parser about 4X in general (enabled when --target-version is set to 3.10 and higher). (#2728)

  • Black is now compiled with mypyc for an overall 2x speed-up. 64-bit Windows, MacOS, and Linux (not including musl) are supported. (#1009, #2431)

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#
  • All upper version bounds on dependencies have been removed (#2718)

  • typing-extensions is no longer a required dependency in Python 3.10+ (#2772)

  • Set click lower bound to 8.0.0 (#2791)

Integrations#
  • Update GitHub action to support containerized runs (#2748)

Documentation#
  • Change protocol in pip installation instructions to https:// (#2761)

  • Change HTML theme to Furo primarily for its responsive design and mobile support (#2793)

  • Deprecate the black-primer tool (#2809)

  • Document Python support policy (#2819)

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#
  • Cell magics are now only processed if they are known Python cell magics. Earlier, all cell magics were tokenized, leading to possible indentation errors e.g. with %%writefile. (#2630)

  • Fix assignment to environment variables in Jupyter Notebooks (#2642)

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, like match a, b: or match a, *b: (#2639) (#2659)

  • Fix match/case statements that contain match/case soft keywords multiple times, like match 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#
  • Remove dependency on regex (#2644) (#2663)

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#
  • Fixed vim plugin with Python 3.10 by removing deprecated distutils import (#2610)

  • The vim plugin now parses skip_magic_trailing_comma from pyproject.toml (#2613)

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#
  • Remove dependency on aiohttp-cors (#2500)

  • Bump required aiohttp version to 3.7.4 (#2509)

Black-Primer#
  • Add primer support for –projects (#2555)

  • Print primer summary after individual failures (#2570)

Integrations#
  • Allow to pass target_version in the vim plugin (#1319)

  • Install build tools in docker file and use multi-stage build to keep the image size down (#2582)

21.9b0#

Packaging#
  • Fix missing modules in self-contained binaries (#2466)

  • Fix missing toml extra used during installation (#2475)

21.8b0#

Black#
  • Add support for formatting Jupyter Notebook files (#2357)

  • Move from appdirs dependency to platformdirs (#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 overriding default_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 only root/.gitignore file (apply .gitignore rules like git 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#
  • Release self-contained x86_64 MacOS binaries as part of the GitHub release pipeline (#2198)

  • Always build binaries with the latest available Python (#2260)

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 the main branch. Some additional changes in the source code were also made. (#2210)

  • Sigificantly reorganized the documentation to make much more sense. Check them out by heading over to the stable docs on RTD. (#2174)

21.5b0#

Black#
  • Set --pyi mode if --stdin-filename ends in .pyi (#2169)

  • Stop detecting target version as Python 3.9+ with pre-PEP-614 decorators that are being called but with no arguments (#2182)

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 specifying exclude in pyproject.toml or on the command line. (#2170)

Packaging#
  • Install primer.json (used by black-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. Now Black 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 fromimport 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 the X-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+ code

    • added --skip-numeric-underscore-normalization to disable the above behavior and leave numeric underscores as they were in the input

    • code 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 preceding yield 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:

    • they now work also within bracket pairs (#329)

    • they now correctly work across function/class boundaries (#335)

    • they now work when an indentation block starts with empty lines or misaligned comments (#334)

  • 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#

  • added --config (#65)

  • added -h equivalent to --help (#316)

  • fixed improper unmodified file caching when -S was used

  • fixed extra space in string unpacking (#305)

  • fixed formatting of empty triple quoted strings (#313)

  • fixed unnecessary slowdown in comment placement calculation on lines without comments

18.6b1#

  • hotfix: don’t output human-facing information on stdout (#299)

  • hotfix: don’t output cake emoji on non-zero return code (#300)

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 spec

  • fixed 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 the unicode_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#

  • fixed parsing of unaligned standalone comments (#99, #112)

  • fixed placement of dictionary unpacking inside dictionary literals (#111)

  • Vim plugin now works on Windows, too

  • fixed unstable formatting when encountering unnecessarily escaped quotes in a string (#120)

18.4a1#

  • added --quiet (#78)

  • added automatic parentheses management (#4)

  • added pre-commit integration (#103, #104)

  • fixed reporting on --check with multiple files (#101, #102)

  • fixed removing backslash escapes from raw strings (#100, #105)

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#

  • don’t remove single empty lines outside of bracketed expressions (#19)

  • added ability to pipe formatting from stdin to stdin (#25)

  • restored ability to format code with legacy usage of async as a name (#20, #42)

  • even better handling of numpy-style array indexing (#33, again)

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 spacing of dots in relative imports (#6, #13)

  • 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/)

Authors#

Glued together by Łukasz Langa.

Maintained with:

Multiple contributions by:

Indices and tables#