简体   繁体   中英

Pylint not understanding an if/else statement?

I have the following example function:

def example(inp):
    if not isinstance(inp, list):
        return 'Not list'
    else:
        return 'List'

>>> example('asdf')
'Not list'
>>> example(['asdf',])
'List'

And yet pylint complains that:

no-else-return: Unnecessary "else" after "return"

Why does it raise that warning, which seems so silly?

Because it is equivalent to this shorter code:

if not isinstance(inp, list):
    return 'Not list'
return 'List'

Specifically, when the body of an if ends with a return , it doesn't matter whether the code for the false condition is in an else or not: it will only be executed if the if condition is false, because if the condition is true, the function will return at the end of the if body.

Pylint seems to prefer the more compact version. But both versions are perfectly correct, and I'd say that sometimes, the if/else version is clearer. Personally, I do if/else if the two bodies are roughly the same size, and only the if if its body is short and the would-be else body is long, thus saving an indentation level for it. Bonus: if you have a long if body and a short else body and the else ends in return (or there's nothing more in the function after the if/else ), negate the condition and end up with a short if body and no else .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM