python.lang.correctness.useless-comparison.no-strings-as-booleans

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

Using strings as booleans in Python has unexpected results. "one" and "two" will return "two". "one" or "two" will return "one". In Python, strings are truthy, and strings with a non-zero length evaluate to True.

Run Locally

Run in CI

Defintion

rules:
  - id: no-strings-as-booleans
    message: Using strings as booleans in Python has unexpected results. `"one" and
      "two"` will return "two". `"one" or "two"` will return "one". In Python,
      strings are truthy, and strings with a non-zero length evaluate to True.
    languages:
      - python
    severity: ERROR
    pattern-either:
      - pattern: |
          if <... "..." and ... ...>:
              ...
      - pattern: |
          if <... "..." or ... ...>:
              ...
      - patterns:
          - pattern-not: |
              if $X in "...":
                ...
          - pattern: |
              if "...":
                  ...
    metadata:
      category: correctness
      technology:
        - python
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]

Examples

useless-comparison.py



# ruleid:no-strings-as-booleans
if "detached HEAD" or "master" in expected:
  pass

# ruleid:no-strings-as-booleans
if ("detached HEAD" or "master" in expected):
  pass

# ruleid:no-strings-as-booleans
if ("detached HEAD" and ("master" in expected)):
  pass

# ok:no-strings-as-booleans
if ("detached HEAD" in expected) and ("master" in expected):
  pass

# ruleid:no-strings-as-booleans
if "":
  pass

# ok:no-strings-as-booleans
if some_id == "foobar":
     pass