Skip to content

prefer-walrus-comprehension-filter

The same call runs in a comprehension filter and its result.

Why

When both evaluations are intended to produce one stable value, repeating the call wastes work and obscures that relationship.

Fix

If reevaluation is unintended, bind the result once in the filter with a fresh containing-scope name and reuse it. Keep separate calls or use an explicit loop when each evaluation is meaningful.

Examples

Before — flagged Comprehension evaluates one call twice
app/values.py
def normalized(values):
return [value.strip() for value in values if value.strip()]
After — preferred Comprehension evaluates the call once
app/values.py
def normalized(values):
return [clean for value in values if (clean := value.strip())]