MartinThoma / flake8-simplify

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

SIM113: Use enumerate #18

Open MartinThoma opened 3 years ago

MartinThoma commented 3 years ago

Explanation

Use 'enumerate' to get a running number over an iterable.

Example

# Bad
idx = 0
for el in iterable:
    ...
    idx += 1

# Good
for idx, el in enumerate(iterable):
    ...
MartinThoma commented 3 years ago

This is a false-positive:

for x in xs:
    cm[x] += 1
pablojadz commented 3 years ago

This is another false possitive

results = []
next_ = 0
for i in range(10):
        if i % 2 == 0:
            continue

        results[next_] = i
        next_ += 1
MartinThoma commented 3 years ago

@pablojadz Could you please run pip install flake8-simplify --upgrade and test again? You should have flake8-simplify==0.14.1 and this issue should not exist anymore.

specke commented 2 years ago

I believe I have another false-positive:

pos = len(output) - token[1]
for __ in range(token[0]):      
    output += output[pos]   
    pos += 1                

This code appends token[0] characters from position pos to the end of the string output. (This is a common pattern in LZ-style decompressors.)

kasium commented 1 year ago

Another possible issues

for idx, el in enumerate([]): pass
print(idx) --> NameError

I would propose to silence the error, when the loop variable is used after the loop