Pylint: useless-else-on-loop only checks for breaks and not returns too

Created on 8 Jan 2017  Â·  5Comments  Â·  Source: PyCQA/pylint

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

Current Behavior:

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.

Expected Behavior:

pylint's useless-else-on-loop check needs to check for return statements as well as break statements.

Pylint Version

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

Most helpful comment

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.

All 5 comments

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

glmdgrielson picture glmdgrielson  Â·  3Comments

sambarluc picture sambarluc  Â·  3Comments

z4y4ts picture z4y4ts  Â·  3Comments

PCManticore picture PCManticore  Â·  3Comments

TBoshoven picture TBoshoven  Â·  3Comments