Skip to content

Python · performance

prefer-walrus-comprehension-filter

python:prefer-walrus-comprehension-filter

Evaluate a repeated comprehension call once with a named expression.

Code
SARJ076
Default
error
Fix
none
Languages
python

Why

Calling the same function in both the filter and result duplicates work and can repeat side effects.

Fix

Bind the result to a fresh meaningful name in the filter and use that name in the comprehension result.

Before / after

Executed by this rule’s unit tests.

Before

Comprehension evaluates one call twice

app/values.py · focus
def collect(values):
    return [compute(value) for value in values if compute(value)]

After

Comprehension evaluates the call once

app/values.py · focus
def collect(values):
    return [result for value in values if (result := compute(value))]

Limits

  • Only single-generator comprehensions inside callable bodies are analyzed.
  • Attribute reads, type-narrowing builtins, differing calls, and filters already using a named expression are excluded.