Black: Question on binary operator linebreaking

Created on 25 Oct 2018  路  2Comments  路  Source: psf/black

Operating system: Linux
Python version: 3.7
Black version: Master

I have the following code:

def test_foo():
    espec = ...
    assert (
        espec.EncodingSpec("e:{A6D4CFE470214878,FD4466FC,n}") ==
        espec.EncodingSpec("e:{A6D4CFE470214878,FD4466FC,n}")
    )

This gets reformatted to the following:

def test_foo():
    espec = ...
    assert espec.EncodingSpec("e:{A6D4CFE470214878,FD4466FC,n}") == espec.EncodingSpec(
        "e:{A6D4CFE470214878,FD4466FC,n}"
    )

The latter is the simpler way to linebreak but is IMO a lot less readable (especially in the case of tests). Is there a case to be made to prefer the former style? I believe that's also how prettier prefers linebreaking as it's a lot more readable in general.

design

Most helpful comment

For reference the line break should be before the operator like this:

    assert (
        espec.EncodingSpec("e:{A6D4CFE470214878,FD4466FC,n}")
        == espec.EncodingSpec("e:{A6D4CFE470214878,FD4466FC,n}")
    )

I have seen the same happen with if statements and personally would prefer this outcome:

if (
    very_long_long_long_long_func('argument') 
    or other_very_long_long_long_func('argument')
):
    pass

to current output:

if very_long_long_long_long_func("argument") or other_very_long_long_long_func(
    "argument"
):
    pass

Somewhat related to issue #571

All 2 comments

For reference the line break should be before the operator like this:

    assert (
        espec.EncodingSpec("e:{A6D4CFE470214878,FD4466FC,n}")
        == espec.EncodingSpec("e:{A6D4CFE470214878,FD4466FC,n}")
    )

I have seen the same happen with if statements and personally would prefer this outcome:

if (
    very_long_long_long_long_func('argument') 
    or other_very_long_long_long_func('argument')
):
    pass

to current output:

if very_long_long_long_long_func("argument") or other_very_long_long_long_func(
    "argument"
):
    pass

Somewhat related to issue #571

I have a code snippet as follows:

        looks_like_pep = (
            file_path.startswith("pep-") and
            file_path.endswith((".txt", "rst")
        )

With line length 79, black re-formats this code to:

        looks_like_pep = file_path.startswith("pep-") and file_path.endswith(
            (".txt", "rst")
        )

Reducing the line length to 75 re-formats the code to:

        looks_like_pep = file_path.startswith(
            "pep-"
        ) and file_path.endswith((".txt", "rst"))

Both outputs are worse IMO than the input here.

ISTM, black more readily breaks around parenthesis than around a binary logical operator.

Was this page helpful?
0 / 5 - 0 ratings