为什么 pylint 抱怨不必要的“elif"?“返回"后(没有其他回报)? [英] why does pylint complain about Unnecessary "elif" after "return" (no-else-return)?

查看:73
本文介绍了为什么 pylint 抱怨不必要的“elif"?“返回"后(没有其他回报)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 pylint 会抱怨这个代码块?

why does pylint complain about this code block?

R1705:不必要的elif"返回"后(无其他返回)

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

解决方案:

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

推荐答案

else 块的目的是定义在条件满足时执行的代码为真,因此不会继续执行到下一个块.

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.

但是,在您的代码中,主条件块有一个 return 语句,这意味着执行将离开函数,因此不需要 else 块:根据定义,返回之后的所有后续代码都不会执行,如果条件为真.这是多余的.它可以用一个简单的 if 代替.

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.

这篇关于为什么 pylint 抱怨不必要的“elif"?“返回"后(没有其他回报)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆