CodeQL 文档

显式返回与隐式(回退)返回混合

ID: py/mixed-returns
Kind: problem
Security severity: 
Severity: recommendation
Precision: high
Tags:
   - reliability
   - maintainability
Query suites:
   - python-security-and-quality.qls

点击查看 CodeQL 代码库中的查询

当函数同时包含显式返回 (return value) 和隐式返回(代码从函数末尾掉落)时,这通常表明遗漏了 return 语句。即使返回 None,最好也返回显式返回值,因为这样可以让其他开发人员更容易阅读您的代码。

建议

在函数末尾添加一个显式返回。

示例

check_state1 函数中,开发人员可能确实打算使用 None 的隐式返回值,因为这等同于 False。但是,check_state2 中的函数更容易阅读。

    def check_state1(state, interactive=True):
        if not state['good'] or not state['bad']:
            if (good or bad or skip or reset) and interactive:
                return                                          # implicitly return None
            if not state['good']:
                raise util.Abort(_('cannot bisect (no known good revisions)'))
            else:
                raise util.Abort(_('cannot bisect (no known bad revisions)')) 
        return True  							                              
           
    def check_state2(state, interactive=True):
        if not state['good'] or not state['bad']:
            if (good or bad or skip or reset) and interactive:
                return False                                    # return an explicit value
            if not state['good']:
                raise util.Abort(_('cannot bisect (no known good revisions)'))
            else:
                raise util.Abort(_('cannot bisect (no known bad revisions)'))
        return True

参考资料

  • ©GitHub, Inc.
  • 条款
  • 隐私