15

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
Rahul Kumar
  • 2,184
  • 3
  • 24
  • 46
zyxue
  • 7,904
  • 5
  • 48
  • 74

1 Answers1

16

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.

Avner Shahar-Kashtan
  • 14,492
  • 3
  • 37
  • 63