This error can be easily reproduced with this function:
def greater_than_20(num):
for i in xrange(num):
if i == 20:
return True
else:
return False
In the above function, the for's else clause will be reached on any function input that is less than 20. However, pylint doesn't believe the else loop will ever be reached because the for loop does not contain a break. So, pylint shows a useless-else-on-loop warning.
pylint's useless-else-on-loop check needs to check for return statements as well as break statements.
> pylint --version
No config file found, using default configuration
pylint 1.6.4,
astroid 1.4.9
Python 2.7.13 (default, Jan 3 2017, 18:59:59)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)]
I disagree with this. The code example presented is equivalent to
def greater_than_20(num):
for i in xrange(num):
if i == 20:
return True
return False
which doesn't contain the else clause.
@degustaf The function was just a simple example.
I think the for-else construct can be useful in more complicated functions. It visually shows that the function will iterate through an iterable and return when encountering one of the elements, or if it doesn't it will do some other logic and return something else. I think that aides code readability 🤷‍♂️.
I also disagree - it is useless else on loop. Documentation clearly states:
When used with a loop, the else clause has more in common with the else clause of a try statement than it does that of if statements: a try statement’s else clause runs when no exception occurs, and a loop’s else clause runs when no break occurs. For more on the try statement and exceptions, see Handling Exceptions.
For me interpretation is simple - else clause on loop has sense only when there's a break statement within a loop.
Thank you @rogalski @degustaf This check is correct, the else clause is superfluous.
ok... i'll let this go then
Most helpful comment
I disagree with this. The code example presented is equivalent to
which doesn't contain the else clause.