Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SIM113: Use enumerate #18

Open
MartinThoma opened this issue Oct 21, 2020 · 5 comments
Open

SIM113: Use enumerate #18

MartinThoma opened this issue Oct 21, 2020 · 5 comments
Assignees
Labels
enhancement New feature or request

Comments

@MartinThoma
Copy link
Owner

MartinThoma commented Oct 21, 2020

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 MartinThoma added the enhancement New feature or request label Oct 21, 2020
@MartinThoma MartinThoma self-assigned this Oct 21, 2020
MartinThoma added a commit that referenced this issue Nov 17, 2020
MartinThoma added a commit that referenced this issue Nov 17, 2020
@MartinThoma
Copy link
Owner Author

This is a false-positive:

for x in xs:
    cm[x] += 1

MartinThoma added a commit that referenced this issue Nov 20, 2020
MartinThoma added a commit that referenced this issue Nov 21, 2020
MartinThoma added a commit that referenced this issue Nov 21, 2020
@MartinThoma MartinThoma changed the title [New Rule] Use enumerate SIM113: Use enumerate Jan 7, 2021
@pablojadz
Copy link

This is another false possitive

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

        results[next_] = i
        next_ += 1

@MartinThoma
Copy link
Owner Author

@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
Copy link

specke commented Sep 18, 2022

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.)

@MartinThoma MartinThoma reopened this Sep 19, 2022
@kasium
Copy link

kasium commented Jul 19, 2023

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

4 participants