Search code examples
pythonif-statementflake8

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


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.


Solution

  • 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