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

Question:

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
Asked By: zyxue

||

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.

Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.