MartinThoma / flake8-simplify

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

[New Rule] Simplify "in dict.keys()" to "in dict" #40

Closed Skylion007 closed 3 years ago

Skylion007 commented 3 years ago

Explanation

Most of the discussion of the motivation about this rule can be found in this very detailed StackOverflow post

Example

# Bad
key in dict.keys()

# Good
key in dict

Basically, the later way of doing this pythonic and slightly more performant and arguably more Readable. The previous method only exists for legacy code (<= python 2.2). So there is no reason to use the former in modern codebases.

MartinThoma commented 3 years ago
$ astpretty --no-show-offsets /dev/stdin <<< `cat example.txt`
Module(
    body=[
        Expr(
            value=Compare(
                left=Name(id='key', ctx=Load()),
                ops=[In()],
                comparators=[
                    Call(
                        func=Attribute(
                            value=Name(id='dict', ctx=Load()),
                            attr='keys',
                            ctx=Load(),
                        ),
                        args=[],
                        keywords=[],
                    ),
                ],
            ),
        ),
    ],
    type_ignores=[],
)