CodeQL 文档

返回长度不同的元组

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

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

函数返回多个参数的常见模式是返回包含这些参数的单个元组。如果函数有多个返回点,则必须注意确保返回的元组长度相同。

建议

确保函数返回长度相似的元组。

示例

在本例中,sum_length_product1 函数同时计算给定列表中值的总和、长度和乘积。但是,对于空列表,返回的元组仅包含列表的总和和长度。在 sum_length_product2 中,此错误已得到纠正。

def sum_length_product1(l):
    if l == []:
        return 0, 0                              # this tuple has the wrong length
    else:
        val = l[0]
        restsum, restlength, restproduct = sum_length_product1(l[1:])
        return restsum + val, restlength + 1, restproduct * val

def sum_length_product2(l):
    if l == []:
        return 0, 0, 1                           # this tuple has the correct length
    else:
        val = l[0]
        restsum, restlength, restproduct = sum_length_product2(l[1:])
        return restsum + val, restlength + 1, restproduct * val

参考资料

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