Black: Unexpected trailing comma left when wrapping up the list parameter inside a function call

Created on 20 Nov 2019  ·  5Comments  ·  Source: psf/black

Describe the bug
Unexpected trailing comma left when wrapping up the list parameter inside a function call.

To Reproduce

Run black on the following snippet:

foo(
    [
        "list",
        "of",
        "values",   
    ]
)

It results in the following output:

foo(
    ["list", "of", "values",]
)

So it left the trailing comma at the end of the list.

Expected behavior
According to the docs regarding trailing commas - "Unnecessary trailing commas are removed if an expression fits in one line" and yet there is trailing comma left at the end. Or maybe I misunderstood the docs?

This wouldn't bug me a lot except for the fact that it triggers a pep8 checker to point it out (pep8 explicitly discourages this behavior here. And since black is strict subset of PEP 8, that should be taken into account, right?

Environment:

  • Version: lack, version 19.10b0
  • OS and Python version: MacOS/Python 3.7.5

Does this bug also happen on master?
Yep, checked with https://black.now.sh/?version=master

Additional context
Thanks for providing awesome formatter! 😄
I'd be willing to help fixing that (if you consider that a bug) if someone could point me into the right direction

bug trailing comma

All 5 comments

This is a bug, output should be

foo(
    [
        "list",
        "of",
        "values",   
    ]
)

I believe if any of nested collections have optional trailing comma, whole line should be exploded

Fixed in PR

I've also noticed this behaviour with function parameters too:

In

def foo(a, b):
    return a + b

something = foo(
    a=120,
    b=240,
)

Out:

def foo(a, b):
    return a + b


something = foo(a=120, b=240,)

black, version 19.10b0

This is an unfortunate consequence of #826. I agree that it should be fixed.

Resolved by #1288 which make the "magic trailing comma" feature generally usable in almost all situations. Now nested trailing commas (and I guess Black thought function parameters/arguments count as nested too) will actually make Black explode the collections.

(black) ichard26@acer-ubuntu:~/programming/oss/black$ git checkout 20.8b1
Note: switching to '20.8b1'.
HEAD is now at 2354126 v20.8b1
(black) ichard26@acer-ubuntu:~/programming/oss/black$ cat temp.py
foo(
    [
        "list",
        "of",
        "values",
    ]
)


def foo(a, b):
    return a + b


something = foo(
    a=120,
    b=240,
)
(black) ichard26@acer-ubuntu:~/programming/oss/black$ black temp.py --diff --color --config tests/empty.toml
All done! ✨ 🍰 ✨
1 file would be left unchanged.

This fix is available in the latest version, 20.8b1. If you the reader are confused by what the "magic trailing comma" feature is, please read the documentation on it.


Environment:

  • Black version: 20.8b1
  • Python version: CPython 3.8.5
  • OS version: Ubuntu 20.04.01 LTS
Was this page helpful?
0 / 5 - 0 ratings