CodeQL queries 1.25
Skip to end of metadata
Go to start of metadata

Name: Testing equality to None

Description: Testing whether an object is 'None' using the == operator is inefficient and potentially incorrect.

ID: py/test-equals-none

Kind: problem

Severity: recommendation

Precision: very-high

Query: EqualsNone.ql
/**
 * @name Testing equality to None
 * @description Testing whether an object is 'None' using the == operator is inefficient and potentially incorrect.
 * @kind problem
 * @tags efficiency
 *       maintainability
 * @problem.severity recommendation
 * @sub-severity high
 * @precision very-high
 * @id py/test-equals-none
 */

import python

from Compare c
where c.getOp(0) instanceof Eq and c.getAComparator() instanceof None
select c, "Testing for None should use the 'is' operator."

When you compare an object to None, use is 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 to None using the is operator is also easier for other programmers to read.

Recommendation

Replace == with is.

Example

The filter2 function is likely to be more efficient than the filter1 function because it uses an identity comparison.

def filter1(function, iterable=None)
    if iterable == None:    # Comparison using '__eq__'
        return [item for item in iterable if item]
    else:
        return [item for item in iterable if function(item)]

def filter2(function, iterable=None)
    if iterable is None:    # Comparison using identity
        return [item for item in iterable if item]
    else:
        return [item for item in iterable if function(item)]

References