跳到内容

multiple-starts-ends-with (PIE810)

派生自 flake8-pie 代码检查工具。

修复总是可用的。

作用

检查对同一值的 startswithendswith 调用,但具有不同的前缀或后缀。

为什么这不好?

startswithendswith 方法分别接受前缀或后缀的元组。传递前缀或后缀的元组比多次调用该方法更有效率和可读性。

示例

msg = "Hello, world!"
if msg.startswith("Hello") or msg.startswith("Hi"):
    print("Greetings!")

建议改为

msg = "Hello, world!"
if msg.startswith(("Hello", "Hi")):
    print("Greetings!")

修复安全性

此规则的修复是不安全的,因为在某些情况下,它将无法确定现有 .startswith.endswith 调用的参数是否为元组。例如,给定 msg.startswith(x) or msg.startswith(y),如果 xy 是一个元组,并且语义模型无法将其检测为元组,则该规则将建议 msg.startswith((x, y)),这将在运行时出错。

参考