跳到内容

assert (S101)

源自 flake8-bandit linter。

作用

检查 assert 关键字的使用。

为什么这不好?

当 Python 在请求优化的情况下运行时(即,当存在 -O 标志时),断言会被删除,这在生产环境中是一种常见做法。 因此,断言不应用于用户输入的运行时验证或强制接口约束。

考虑引发一个有意义的错误,而不是使用 assert

示例

assert x > 0, "Expected positive value."

建议改为

if not x > 0:
    raise ValueError("Expected positive value.")

# or even better:
if x <= 0:
    raise ValueError("Expected positive value.")