astral-sh / ruff

An extremely fast Python linter and code formatter, written in Rust.
https://docs.astral.sh/ruff
MIT License
31.83k stars 1.07k forks source link

Add support for optional trailing comma #9389

Closed 17Reset closed 3 months ago

17Reset commented 9 months ago

When I format my code using ruff format, after the format, there is always a comma after the code, can this be avoided by a parameter? For example, my source code:

FILE_SUFFIX_ICON = {
    MATLAB_SUFFIX: MATLAB_ICON,
    CPP_SUFFIX: CPP_ICON,
    SV_SUFFIX: RTL_ICON,
    'Default': FILE_ICON
}

After using format:

FILE_SUFFIX_ICON = {
    MATLAB_SUFFIX: MATLAB_ICON,
    CPP_SUFFIX: CPP_ICON,
    SV_SUFFIX: RTL_ICON,
    'Default': FILE_ICON,
}
tjkuson commented 9 months ago

The Ruff formatter tries to follow the Black code style, which adds a trailing comma. A configuration option has not been added to Ruff to change that behaviour (it would have to be a new feature).

Related discussion: #9350

17Reset commented 9 months ago

Thanks, hope to add this feature option.

MichaReiser commented 9 months ago

There's no such option today. Would you mind explaining your motivation for omitting the trailing comma?

Ruff supports the --skip-magic-trailing-comma option. It doesn't configure whether the trailing comma should be added, but it removes the trailing comma (and flattens the entries in the above example), if they all fit on a single line, e.g. after deleting or changing an entry.

heiner commented 3 months ago

Here's a reason this might be useful: It turns ruff format into a quite decent json formatting engine. E.g.,

cat file.json | ruff format - --isolated --config indent-width=2

However, sadly trailing commas aren't legal JSON.

MichaReiser commented 3 months ago

You may want to give Biome a try if you are looking for a Rust based JSON formatter.

MichaReiser commented 3 months ago

I'm closing this as not planned. Feel free to open a new issue to discuss the style with an outline for the use case and benefit of omitting trailing commas.

17Reset commented 3 months ago

It's not a popular style for trailing commas to appear after line breaks in Python lists, is it?

heiner commented 3 months ago

You may want to give Biome a try if you are looking for a Rust based JSON formatter.

That's less useful as a quick-and-dirty way to format JSON within Python code, where the existence of ruff is more or less guaranteed.

Still, ack'd on this being a bit fringe.

mshahbazi commented 1 month ago

The issue arises when the formatter adds a trailing comma, which prevents the code from being one-liner, when shortened, due to the presence of the comma, unless the trailing comma is removed manually.

nyssance commented 10 hours ago

Black style for trailing comma is stupid.