Testing equality to None¶
ID: py/test-equals-noneKind: problemSecurity severity: Severity: recommendationPrecision: very-highTags: - quality - reliability - correctness - performanceQuery suites: - python-security-and-quality.qls
Click to see the query in the CodeQL repository
When you compare an object toNone, useis rather than==.None is a singleton object, comparing using== invokes the__eq__ method on the object in question, which may be slower than identity comparison. Comparing toNone using theis operator is also easier for other programmers to read.
Recommendation¶
Replace== withis.
Example¶
Thefilter2 function is likely to be more efficient than thefilter1 function because it uses an identity comparison.
deffilter1(function,iterable=None)ifiterable==None:# Comparison using '__eq__'return[itemforiteminiterableifitem]else:return[itemforiteminiterableiffunction(item)]deffilter2(function,iterable=None)ifiterableisNone:# Comparison using identityreturn[itemforiteminiterableifitem]else:return[itemforiteminiterableiffunction(item)]
References¶
Python Language Reference:Comparisons,object.eq.