Compare to None with is
ID |
python.none_comparison_identity |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Best Practice |
Language |
Python |
Tags |
best-practice, suspicious-comparison |
Description
Reports x == None or x != None comparisons. Python’s idiom is identity comparison (x is None / x is not None); equality comparison routes through eq, which a custom class can override to return something surprising for the None case (most often a NumPy / pandas object whose eq returns an element-wise array).
if x == None: # FLAW
...
if x != None: # FLAW
...
if x is None: # OK
...
Rationale
None is a singleton. There is exactly one None object in the running interpreter, so identity comparison is both correct and faster than the equality variant. Identity comparison also bypasses eq, which is what you almost always want when checking for None: a custom eq that decides "I’m equal to anything" or "I return an array" silently breaks the test.