Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does pylint complain about Unnecessary "elif" after "return" (no-else-return)?

Tags:

pylint

why does pylint complain about this code block?

R1705: Unnecessary "elif" after "return" (no-else-return)

def f(a):
    if a == 1:
        return 1
    elif a == 2:
        return 2
    return 3

To prevent the error, I had to create a temporary variable, which feels less pleasant.

def f(a):
    if a == 1:
        b = 1
    elif a == 2:
        b = 2
    else:
        b = 3

    return b

Solution:

def f(a):
    if a == 1:
        return 1
    if a == 2:
        return 2
    return 3
like image 223
zyxue Avatar asked Sep 05 '20 16:09

zyxue


1 Answers

The purpose of an else block is to define code that will not be executed if the condition is true, so execution wouldn't continue on to the next block.

However, in your code, the main conditional block has a return statement, meaning execution will leave the function, so there's no need for an else block: all subsequent code after the return will, by definition, not be executed if the condition is true. It's redundant. It can be replaced with a simple if.

like image 183
Avner Shahar-Kashtan Avatar answered Oct 25 '22 04:10

Avner Shahar-Kashtan