astral-sh / ruff

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

New Rule + fixer: Use a list instead of calling split with string literals #13944

Closed Avasam closed 5 minutes ago

Avasam commented 5 days ago

I've seen this pattern a handful of time:

"""
    itemA
    itemB
    itemC
""".split()

or

"a,b,c,d".split(",")

And I'd like a rule to transform usages of join with literals into actual inline lists without the overhead of calling "join". My two examples above would become:

[
    "itemA",
    "itemB",
    "itemC",
]

or

["a", "b", "c", "d"]

I don't think this rule exists in any linters that I'm aware of.

The exact details of how this gets formatted isn't important to this rule. Probably just rewrite everything on a single line and let formatting/other rules take care of the rest.

sbrugman commented 4 days ago

Great suggestion, I think it's worth adding. With autofix this adds to developer experience as writing the comma-seperated pattern is sometimes just more convenient.

Real-world examples:

Similar rule: https://docs.astral.sh/ruff/rules/static-join-to-f-string/

MichaReiser commented 3 days ago

This seems reasonable. Although I'm somewhat surprised that people do this :D

The comma pattern seems easy enough to detect. The split without a separator needs some extra care to ensure we apply the exact same logic.

sbrugman commented 2 days ago

For posterity, @AlexWaygood noticed that this rule exists in flake8-simplify: https://github.com/MartinThoma/flake8-simplify/issues/86 (SIM905)