CodeQL 文档

格式化调用中缺少命名参数

ID: py/str-format/missing-named-argument
Kind: problem
Security severity: 
Severity: error
Precision: high
Tags:
   - reliability
   - correctness
Query suites:
   - python-security-and-quality.qls

点击查看 CodeQL 仓库中的查询

格式化表达式,即 the_format.format(args)format(the_format, args) 形式的表达式,可以使用命名字段。如果使用命名字段,则必须为所有命名字段提供关键字参数。如果缺少任何关键字参数,则将引发 KeyError

建议

更改格式以匹配参数,并确保参数具有正确的名称。

示例

在以下示例中,如果 unlikely_condition() 为真,则将引发 KeyError,因为缺少关键字参数 eggs。添加一个名为 eggs 的关键字参数可以解决此问题。

def unsafe_named_format():
    the_format = "{spam} {eggs}"
    if unlikely_condition():
        return the_format.format(spam="spam", completely_different="eggs")
    else:
        return the_format.format(spam="spam", eggs="eggs")

参考文献

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