5
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.

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Mr Singh
  • 3,936
  • 5
  • 41
  • 60
  • Possible duplicate of [Python booleans - if x:, vs if x == True, vs if x is True](https://stackoverflow.com/questions/20420934/python-booleans-if-x-vs-if-x-true-vs-if-x-is-true) – Kos Jun 13 '18 at 11:55
  • 1
    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. – Kos Jun 13 '18 at 11:56

2 Answers2

6

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
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • 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? – Svenito Jul 11 '23 at 11:10
  • @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. – Willem Van Onsem Jul 11 '23 at 11:31
2

The error msg is saying you to use this syntax.

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

You do not need to mention == True

Rakesh
  • 81,458
  • 17
  • 76
  • 113