python.lang.correctness.common-mistakes.is-not-is-not.is-not-is-not

Verifed by r2c
Community Favorite
profile photo of semgrepsemgrep
Author
66,422
Download Count*

In Python 'X is not ...' is different from 'X is (not ...)'. In the latter the 'not' converts the '...' directly to boolean.

Run Locally

Run in CI

Defintion

rules:
  - id: is-not-is-not
    message: In Python 'X is not ...' is different from 'X is (not ...)'. In the
      latter the 'not' converts the '...' directly to boolean.
    languages:
      - python
    severity: ERROR
    pattern: $S is (not ...)
    metadata:
      category: correctness
      technology:
        - python
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]

Examples

is-not-is-not.py

x = 'foo'

# ruleid: is-not-is-not
if x is (not 'hello there'):
    pass

# ruleid: is-not-is-not
if x is (not None):
    pass

# OK
if x is not None:
    pass