python.lang.correctness.useless-eqeq.useless-eqeq

Verifed by r2c
Community Favorite
profile photo of semgrepsemgrep
Author
124,743
Download Count*

This expression is always True: $X == $X or $X != $X. If testing for floating point NaN, use math.isnan($X), or cmath.isnan($X) if the number is complex.

Run Locally

Run in CI

Defintion

rules:
  - id: useless-eqeq
    patterns:
      - pattern-not-inside: |
          def __eq__(...):
              ...
      - pattern-not-inside: |
          def __cmp__(...):
              ...
      - pattern-not-inside: assert(...)
      - pattern-not-inside: assert ..., ...
      - pattern-not-inside: assertTrue(...)
      - pattern-not-inside: assertFalse(...)
      - pattern-either:
          - pattern: $X == $X
          - pattern: $X != $X
      - pattern-not: 1 == 1
    message: "This expression is always True: `$X == $X` or `$X != $X`. If testing
      for floating point NaN, use `math.isnan($X)`, or `cmath.isnan($X)` if the
      number is complex."
    languages:
      - python
    severity: INFO
    metadata:
      category: correctness
      technology:
        - python
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]

Examples

useless-eqeq.py


# ruleid:useless-eqeq
x == x

def __eq__(self, other):
    # ok:useless-eqeq
    return self == self and self == other

def sure(ofcourse):
    # ok:useless-eqeq
    return 1 == 1

class A:
    def __eq__(self, other):
        # ok:useless-eqeq
        return self == self and self == other


# ok:useless-eqeq
assert(x == x)
# ok:useless-eqeq
assert x == x
# ok:useless-eqeq
assert x == x, "of course"
# ok:useless-eqeq
assertTrue(x ==x)
# ok:useless-eqeq
assertFalse(x == x)

# ruleid:useless-eqeq
print(x != x)