MartinThoma / flake8-simplify

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

[Adjust Rule] SIM110 #34

Closed MartinThoma closed 2 years ago

MartinThoma commented 3 years ago

Desired change

Example

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

#  Code
for el in [1,2,3]:
    if is_true(el):
        return True
raise Exception

# Current message
SIM110 Use 'return any(is_true(el) for el in [1, 2, 3])'

# Desired message: Either none or the following:
SIM110 Use 'if any(is_true(el) for el in [1, 2, 3]): return True; raise Exception'
MartinThoma commented 3 years ago

Going in a similar direction, in the following example the rule should also not be triggered:

for symbol_pred in pred_seg:
    for symbol_real in real_seg:
        if symbol_pred[0] in symbol_real:
            for stroke in symbol_pred:
                if stroke not in symbol_real:
                    return True
return False
MartinThoma commented 3 years ago

Checking for the exception case is actually not that easy. Doing it requires not only to get the parent node of the first for-loop, but to get the next sibling of that for-loop. There could be multiple for-loops within the parent.

MartinThoma commented 2 years ago

Add a test:

def test_sim110_other_false_positive():
    ret = _results(
        """for symbol_pred in pred_seg:
    for symbol_real in real_seg:
        if symbol_pred[0] in symbol_real:
            for stroke in symbol_pred:
                if stroke not in symbol_real:
                    return True
return False"""
    )
    for el in ret:
        assert "SIM110" not in el