Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Trailing Comma in Dictionary not working if a comment line is at the end #3072

Closed
Cattes opened this issue May 13, 2022 · 1 comment · Fixed by #3393
Closed

Trailing Comma in Dictionary not working if a comment line is at the end #3072

Cattes opened this issue May 13, 2022 · 1 comment · Fixed by #3393
Labels
F: trailing comma Full of magic T: bug Something isn't working

Comments

@Cattes
Copy link

Cattes commented May 13, 2022

Describe the bug

When running black on a dictionary with a comment, a trailing comma is not set correctly
The example

{
    "a": fun(msg, "ts"),
    "longggggggggggggggid": ...,
    "longgggggggggggggggggggkey": ..., "created": ...
    # "longkey": ...
}

is being formatted to

{
    "a": fun(msg, "ts"),
    "longggggggggggggggid": ...,
    "longgggggggggggggggggggkey": ...,
    "created": ...
    # "longkey": ...
}

where the , is missing after "created": ...

To Reproduce

The bug can be reproduced using black.vercel.app

Expected behavior
The expected behavior would create a format with the trailing comma set at the end of the last dictionary entry:

{
    "a": fun(msg, "ts"),
    "longggggggggggggggid": ...,
    "longgggggggggggggggggggkey": ...,
    "created": ...,
    # "longkey": ...
}

Environment

  • Black's version: 22.3.0
  • OS and Python version: Linux/Python 3.9.7

Additional context

I had a look at the code yesterday, and I got the black dev environment locally up and running (great job with that btw, worked on the first try) and set up the test case that is failing, and went into black._format_str_once with a debugger to understand what is happening.

I landed at black.linegen.delimiter_split() where I think the source of the issue lies, but I am not sure about that.

I got to this chunk of code, where the current_line is checked and always the last leave is selected and checked. If I understand correctly by some backwards looping through the line leaves.

image

When I let the debugger iterate and always check, what current_line.leaves[-1] prints, it always prints the last comment line # "longkey": .... Not sure if I am on the right track though.

@mainj12
Copy link
Contributor

mainj12 commented Nov 22, 2022

I've made a proposed fix, see PR - #3393

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
F: trailing comma Full of magic T: bug Something isn't working
Projects
None yet
3 participants