gpt4 book ai didi

python - Flake8 错误 : E712 comparison to True should be 'if cond is True:' or 'if cond:'

转载 作者:行者123 更新时间:2023-11-28 22:18:01 26 4
gpt4 key购买 nike

if user.item.purchase.status == True:

...使用 flake8 检查时产生错误:

E712 comparison to True should be 'if cond is True:' or 'if cond:'

status 具有三个有效值:Undefined、True 和 False。

最佳答案

如果status 是一个 bool 值,那么写expr == True 就很奇怪了,因为True == TrueTrueFalse == TrueFalse,我们可以简单地写成expr .

另一方面,如果 status 本身不是 boolean,那么比较将尝试检查对象是否value equals to True,这可能是不同的,但通常“奇怪”的是某个对象等于 TrueFalse 。例如 1 == True 成立,但 1True不同对象。

如果 status 可以是非 bool 值,并且您想检查状态是否真的 True(所以不是value 相等,但 reference 相等),则可以使用 is 检查,因为 exp1 is exp2 检查如果两个变量引用同一个对象。

但是,如果您将表达式写为条件,例如 if expr,则 Python 会评估该表达式的真实性。例如,非空列表的真实性是True,而对于空集合,它通常是False。由于 TrueFalse 的真实性分别为 TrueFalse,因此不需要编写 == True 在这种情况下。

我认为这里的 status 可能是一个 BooleanField,所以在那种情况下你可以这样写:

if <b>user.item.purchase.status:</b>
# ...
pass

关于python - Flake8 错误 : E712 comparison to True should be 'if cond is True:' or 'if cond:' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50836584/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com