python.lang.correctness.common-mistakes.is-comparison-string.string-is-comparison

Verifed by r2c
Community Favorite
profile photo of semgrepsemgrep
Author
89,146
Download Count*

Found string comparison using 'is' operator. The 'is' operator is for reference equality, not value equality, and therefore should not be used to compare strings. For more information, see https://github.com/satwikkansal/wtfpython#-how-not-to-use-is-operator"

Run Locally

Run in CI

Defintion

rules:
  - id: string-is-comparison
    patterns:
      - pattern-not: $S is None
      - pattern-not: type($X) is $T
      - pattern-not: $S is True
      - pattern-not: $S is False
      - pattern-not: $S is ""
      - pattern-either:
          - pattern: $S is "..."
          - pattern: '"..." is $S'
    message: Found string comparison using 'is' operator. The 'is' operator is for
      reference equality, not value equality, and therefore should not be used
      to compare strings. For more information, see
      https://github.com/satwikkansal/wtfpython#-how-not-to-use-is-operator"
    languages:
      - python
    severity: ERROR
    metadata:
      category: correctness
      technology:
        - python
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]

Examples

is-comparison-string.py

x = object()

# ruleid:identical-is-comparison
if x is x:
  print('true')

# ok:identical-is-comparison
if x is None:
  pass

# ok:identical-is-comparison
if (type(X) is str):
  pass

# ok:identical-is-comparison
if x is True:
  pass

# ok:identical-is-comparison
if x is False:
  pass

# ruleid: string-is-comparison
if x is 'hello there':
  pass

# ruleid: string-is-comparison
if "hello there" is x:
  pass

# ok: string-is-comparison
if x is '':
  pass