python.lang.maintainability.improper-list-concat.improper-list-concat

profile photo of semgrepsemgrep
Author
unknown
Download Count*

This expression will evaluate to be ONLY value the of the else clause if the condition $EXPRESSION is false. If you meant to do list concatenation, put parentheses around the entire concatenation expression, like this: ['a', 'b', 'c'] + (['d'] if x else ['e']). If this is the intended behavior, the expression may be confusing to others, and you may wish to add parentheses for readability.

Run Locally

Run in CI

Defintion

rules:
  - id: improper-list-concat
    languages:
      - python
    message: "This expression will evaluate to be ONLY value the of the `else`
      clause if the condition `$EXPRESSION` is false. If you meant to do list
      concatenation, put parentheses around the entire concatenation expression,
      like this: `['a', 'b', 'c'] + (['d'] if x else ['e'])`. If this is the
      intended behavior, the expression may be confusing to others, and you may
      wish to add parentheses for readability."
    metadata:
      category: maintainability
      technology:
        - python
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]
    pattern: "[...] + [...] if $EXPRESSION else [...]"
    severity: INFO

Examples

improper-list-concat.py

x = False
# ruleid: improper-list-concat
['a', 'b', 'c'] + ['d'] if x else []

x = 1234
# ruleid: improper-list-concat
['a', 'b', 'c'] + ['d'] if x > 1000 else ['e']

# ok: improper-list-concat
['a', 'b', 'c'] + (['d'] if x > 1000 else ['e'])