Flake8 error: E712 comparison to True should be 'if cond is True:' or 'if cond:'
Asked Answered
M

2

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

...produces an error when checking with flake8:

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

status has three valid values: Undefined, True, and False.

Manhattan answered 13/6, 2018 at 11:52 Comment(2)
Possible duplicate of Python booleans - if x:, vs if x == True, vs if x is TrueStrapping
Long story short, if user.item.purchase.status checks for truthiness, while if user.item.purchase.status is True checks if the value is exactly True. The linter wants you to decide to use one or the other. The linked answer has more details.Strapping
M
9

Well in case status is a boolean, then it is strange to write expr == True, since True == True is True, and False == True is False, we can simply write expr instead.

If on the other hand status is something that is not per se a boolean, then the comparison will try to check if the object value equals to True, which can be different, but usually it is "strange" that some object is equal to True or False. For example 1 == True holds, but 1 and True are different objects.

In case status is something that can be a non-boolean, and you want to check if status is really True (so not the value equality, but reference equality), then the is check can be used, since exp1 is exp2 checks if the two variables refer to the same object.

If you however write an expression as condition, like if expr, then Python evaluates the truthiness of that expression. For example the truthiness of a non-empty list is True, whereas for an empty collection, it is usually False. Since the truthiness of True and False are True and False respectively, there is thus no need to write == True in that case.

I think here status is probably a BooleanField, so in that case you can write:

if user.item.purchase.status:
    # ...
    pass
Maltose answered 13/6, 2018 at 11:56 Comment(2)
Why does flake8 recommend 'if cond is True', when PEP8 clearly states that 'if cond' is best, 'if cond == True' is wrong but 'if cond is True' is worse?Orland
@Svenito: the two are not equivalent. if x is True means it will suceed if x is indeed the boolean True, whereas if x will suceed if x has truthiness True, this means any non-zero integer, any non-empty list, tuple, string, etc.Maltose
P
3

The error msg is saying you to use this syntax.

if user.item.purchase.status:
    #Do Stuff

You do not need to mention == True

Peltz answered 13/6, 2018 at 11:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.