处理不一致 Return 语句的 PyLint 警告

Handling PyLint Warning of Inconsistent Return Statement

我正在 运行 PyLint 处理一些代码,我收到 "Either all return statements in a function should return an expression or none of them should. (inconsistent-return-statements)."

的警告

这是我的代码:

def determine_operand_count(opcode_form, opcode_byte):
  if opcode_form == OP_FORM.VARIABLE:
    if opcode_byte & 0b00100000 = 0b00100000:
      return OP_COUNT.VAR

    return OP_COUNT.OP2

  if opcode_form == OP_FORM.SHORT:
    if opcode_byte & 0b00110000 == 0b00110000:
      return OP_COUNT.OP0

    return OP_COUNT.OP1

  if opcode_form == OP_FORM.LONG:
    return OP_COUNT.OP2

这里 "OP_FORM" 和 "OP_COUNT" 是代码前面定义的枚举。

对我来说,该代码是非常可读的代码,我想我很好奇 PyLint 的警告在抱怨什么。在我遇到的每一种情况下,"OP_COUNT" 类型都是 returned。事实上,如果这些条件中的任何一个不是 returning 一个 OP_COUNT,我的代码将完全失败。

这似乎是对我的 "return statements" 的警告,暗示有些人没有 returning 任何类型的表达。但这显然不是真的(据我所知),因为每个 return 语句都是 returning 东西。所以我猜这与隐含的 returns?

有关

但到那时,在我的原始代码中,我实际上为我的内部 if 语句保留了 "else" 子句。但是当我这样做时,PyLint 给了我另一个警告:"Unnecessary 'else' after 'return' (no-else-return)."

我确实看到了以下内容:“”,但这似乎并没有反映我的代码中的情况。

所以我不清楚在这种情况下如何满足 PyLint,因为代码显然有效并且似乎正在执行警告建议我需要执行的操作。鉴于此,我怀疑我遗漏了一些明显的东西,但我目前缺乏发现的直觉。任何能让我发现我遗漏的东西的帮助都将不胜感激。

对于您的情况,可能有两个原因:

1) 由于某种原因,您的变量名称大小写不一致:第一个 if 语句中的 opcode_Form(大写 "F")(可能您只是打错了,因为您也= 而不是 == 在同一个地方)和 opcode_form (小写 "f")在所有其他地方。

2) 更可能的是,由于 opcode_form 没有类型提示作为 OP_FORM 枚举实例,它实际上可以是任何值,最后的 else (对于opcode_form 既不是 OP_FORM.VARIABLE 也不是 OP_FORM.SHORTOP_FORM.LONG) 的情况丢失了。因此,例如,如果 opcode_form 是某个字符串 "string",该函数实际上 return 什么都没有。

Pylint 抱怨当你到达函数的最后时发生了什么。函数结束时应该发生什么? (添加了 return 并且警告消失了)

def determine_operand_count(opcode_form, opcode_byte):
    if opcode_form == OP_FORM.VARIABLE:
        if opcode_byte & 0b00100000 == 0b00100000:
            return OP_COUNT.VAR
        return OP_COUNT.OP2

    if opcode_form == OP_FORM.SHORT:
        if opcode_byte & 0b00110000 == 0b00110000:
            return OP_COUNT.OP0
        return OP_COUNT.OP1

    if opcode_form == OP_FORM.LONG:
        return OP_COUNT.OP2

    return OP_COUNT.UNKNOWN

这段代码应该可以工作,但根据我的经验,由于缩进,随着时间的推移会变得脆弱。另一种方法是将其写为:

def determine_operand_count_v2(opcode_form, opcode_byte):
    def variable_form(opcode_byte):
        if opcode_byte & 0b00100000 == 0b00100000:
            return OP_COUNT.VAR
        return OP_COUNT.OP2

    def short_form(opcode_byte):
        if opcode_byte & 0b00110000 == 0b00110000:
            return OP_COUNT.OP0
        return OP_COUNT.OP1

    def long_form(_):
        return OP_COUNT.OP2

    opfcn = {OP_FORM.VARIABLE: variable_form,
             OP_FORM.SHORT: short_form,
             OP_FORM.LONG: long_form}

    return opfcn[opcode_form](opcode_byte)