python/comprehension-two-fors
| Pack | Severity | Fix | Versions |
|---|---|---|---|
| Python | warning | unsafe, with xpd check --fix --unsafe-fixes |
All versions |
A comprehension with more than one for is hard to read. Write a nested loop, or flatten with [*xs for xs in lists] on Python 3.15.
def checks(cases): return [check for case in cases for check in case.checks] found = [] for case in cases: found.extend(case.checks) return foundWhat the rule reports
Section titled “What the rule reports”The rule reports a comprehension or generator expression with more than one for.
How to fix it
Section titled “How to fix it”Inside a function, xpd can write nested loops for a list or dict comprehension in a return, an assignment, or a call argument. The loop variables get fresh names when the originals would collide with other uses in the function. Generator expressions keep their lazy evaluation and require a manual rewrite.
Apply the fix with xpd check --fix --unsafe-fixes. The additional locals and the lifetime of their values are observable.
The clauses run in the order of a nested loop, but the result stands before both of them. A
reader has to reorder the expression to follow it. On Python 3.15,
[*case.checks for case in cases] flattens the lists with one for.
Diagnostic message
Section titled “Diagnostic message”This comprehension has more than one for. Write a nested loop, or flatten with [*xs for xs in lists] on Python 3.15.See all rules in the Python pack.