pylint
pylint copied to clipboard
Catch accidentally exhausting iterators by repeatedly looping through them
Is your feature request related to a problem? Please describe
iterator = (ord(char) for char in string.printable)
for spam in range(10):
for eggs in iterator: # this won't work as expected and is really hard to catch!
print(chr(spam*eggs))
Describe the solution you'd like
W\d+: Repeatedly looping through iterator (looping-through-iterator)
Additional context
I realize it's easy to have false positives here, but if we limit to cases where it's clear that it's a non-infinite iterator (e.g. list(iterable)
, comprehensions, for loops without return/break/continue) I think the main problem is that I could have used range(1) above and that would give a false positive, but that seems like fairly bad style anyway.
Yeah, this might be tricky to get right, but it would an useful check to have.