MartinThoma / flake8-simplify

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

[Adjust Rule] SIM 108 and SIM 118 don't cover enough cases as Ruff #193

Open Emilianissimo opened 8 months ago

Emilianissimo commented 8 months ago

Desired change

Explanation

For SIM118 package cannot handle any NotIn type of expressions, only In, which is not covering one of cases. For SIM108 package ignores the case when line of new code is more than 79 characters, which should adjusted as warning of line length and shoudn't be ignored. Ruff, for example can determine them.

Example

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

# SIM118
if key in dict.keys():  # returns the rule error
    ...
if key not in dict.keys():  # ignores
    ...

# SIM108
if a:
    b = c
else:
   b = d
# New code will be less than 79 and error will not be ignored

if long_varialbe_name:
    long_one_second = something_if
else:
    long_one_second = something_else
# New code wil exceed 79 length and error will be igonred

Soltions


# Solution for ast_compare.py:get_sim118
...
RULE = "SIM118 Use '{el} in {dict}' instead of '{el} in {dict}.keys()'"
errors: List[Tuple[int, int, str]] = []
if not (
    len(node.ops) == 1
    and (
            isinstance(node.ops[0], ast.In) or
            isinstance(node.ops[0], ast.NotIn)  # here is the new case
    )
    and len(node.comparators) == 1
):
     return errors
...

# Solution for ast_if.py:get_sim108
...
new_code = RULE.format(assign=assign, body=body, cond=cond, orelse=orelse)
    if len(new_code) > 79:
        new_code += '. This line will exceed 79 characters, please, be sure, that you will control it.'  # now all cases will not be ignored and just add new warning to it
    errors.append((node.lineno, node.col_offset, new_code))
...