MartinThoma / flake8-simplify

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

[Adjust Rule] SIM118: for key in list(dict.keys) can be used if the loop removes keys #46

Closed MartinThoma closed 3 years ago

MartinThoma commented 3 years ago

Desired change

Explanation

The change would actually introduce a bug

Example

This is an example where the mentioned rule(s) would currently be suboptimal:

# Before
for key in list(dict.keys()):
    if some_property(key):
        del dict[key]

# After (wrong?)
for key in dict:
    if some_property(key):
        del dict[key]
MartinThoma commented 3 years ago
        For(
            target=Name(id='key', ctx=Store()),
            iter=Call(
                func=Attribute(
                    value=Name(id='dict', ctx=Load()),
                    attr='keys',
                    ctx=Load(),
                ),
                args=[],
                keywords=[],
            ),
            body=[
                If(
                    test=Compare(
                        left=Name(id='key', ctx=Load()),
                        ops=[In()],
                        comparators=[
                            List(
                                elts=[
                                    Constant(value='a', kind=None),
                                    Constant(value='c', kind=None),
                                ],
                                ctx=Load(),
                            ),
                        ],
                    ),
                    body=[
                        Delete(
                            targets=[
                                Subscript(
                                    value=Name(id='dict', ctx=Load()),
                                    slice=Name(id='key', ctx=Load()),
                                    ctx=Del(),
                                ),
                            ],
                        ),
                    ],
                    orelse=[],
                ),
            ],
            orelse=[],
            type_comment=None,
        )
MartinThoma commented 3 years ago
Delete(
                            targets=[
                                Subscript(
                                    value=Name(id='dict', ctx=Load()),
                                    slice=Name(id='key', ctx=Load()),
                                    ctx=Del(),
                                ),
                            ],
                        ),