CodeQL documentation

Testing equality to None

ID: py/test-equals-none
Kind: problem
Security severity: 
Severity: recommendation
Precision: very-high
Tags:
   - quality
   - reliability
   - correctness
   - performance
Query suites:
   - python-security-and-quality.qls

Click to see the query in the CodeQL repository

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

  • © GitHub, Inc.
  • Terms
  • Privacy
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy