MartinThoma / flake8-simplify

❄ A flake8 plugin that helps you to simplify code
MIT License
186 stars 19 forks source link

[New Rule] Create dictionary directly #92

Closed atombrella closed 2 years ago

atombrella commented 2 years ago

Explanation

Do not use a line to create a dictionary, and then populate it. Do it directly. PyCharm has this check, which is rather neat; I think it's in Pylint as I think this linter is used behind the scenes when you run code inspection on a project. It's a bit faster (nanoseconds, whatever), and it reads nicer.

Example

# Bad
a = {}
a['b] = 'c'

# Good
a = {'b': 'c'}
MartinThoma commented 2 years ago
$ astpretty --no-show-offsets /dev/stdin <<< `cat example.txt`
Module(
    body=[
        Assign(
            targets=[Name(id='a', ctx=Store())],
            value=Dict(keys=[], values=[]),
            type_comment=None,
        ),
        Assign(
            targets=[
                Subscript(
                    value=Name(id='a', ctx=Load()),
                    slice=Constant(value='b', kind=None),
                    ctx=Store(),
                ),
            ],
            value=Constant(value='c', kind=None),
            type_comment=None,
        ),
    ],
    type_ignores=[],
)
MartinThoma commented 2 years ago

One would need to acct on ast.Assign (=node)

Then it could be added to the node directly.