Boolean Comparison With Literal
ID |
python.boolean_compare_with_literal |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Best Practice |
Language |
Python |
Tags |
best-practice, code-style |
Description
Reports comparisons against the True or False literals using == or !=. The whole expression collapses to the operand itself (or its negation), so the literal adds noise without information.
Identity comparisons (is / is not) are intentionally not flagged: they have stricter semantics than truthiness — x is True only matches the True singleton, whereas if x: accepts any truthy value — so they are not equivalent and rewriting them would change behaviour.
if x == True: # FLAW — same as `if x:`
...
if x == False: # FLAW — same as `if not x:`
...
if x is True: # OK — identity check, stricter than truthiness
...
if x: # OK
...
if not x: # OK
...
Rationale
The longer form invites a subtle bug: x == True is False for any truthy non-True value (e.g. 1, "yes", a non-empty list)[1], while if x: gives the correct truthy semantics. PEP 8 recommends the shorter form for that reason.
Remediation
if x: # was: if x == True:
...
if not x: # was: if x == False:
...
If the intent really is to require the singleton True (e.g., a contract that says "the function must return True, not just truthy"), keep the comparison using is / is not.
1 == True is True because True is a subclass of int with value 1, but 2 == True is False, and so is "yes" == True.