Search code examples
pythonformattingpython-black

Disable Black formatting of dict expression within mapping comprehensions


I'm currently researching Black as our default formatter, but, I'm having some edge cases that don't format well and I want to know if there's a way to get the result I want.

Black's documentation partially explores my problem, I have a dictionary expression spread horizontally, and I want to keep it that way since I'm expecting lines to be added, e.g.:

# Black would keep this as-is because of the trailing comma
TRANSLATIONS = {
    "en_us": "English (US)",
    "pl_pl": "polski",
}

But in my case the dictionary is inside a list comprehension:

res = [
    {
        'id': item.id,
        'name': item.name,
    }
    for item in items.select()
]

Which Black collapses, regardless of the trailing comma, like so:

res = [
    {"id": item.id, "name": item.name,}
    for item in items.select()
]

Is there a way of telling Black to retain the horizontal structure in these cases?


Solution

  • It seems that black addressed this issue.

    At the time of writing this answer, using black version 20.8b1, the formatting is done as I was hoping for.

    As long as there is a magic trailing comma on the last item in the dictionary expression, black will format the code within the list comprehension.

    res = [
        {
            "id": item.id, "name": item.name,
        }
        for item in items.select()
    ]
    

    Will format to:

    res = [
        {
            "id": item.id,
            "name": item.name,
        }
        for item in items.select()
    ]