Skip to content

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

@Cattes

Description

@Cattes

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions