python/comprehension-among-arguments
| Pack | Severity | Fix | Versions |
|---|---|---|---|
| Python | warning | unsafe, with xpd check --fix --unsafe-fixes |
All versions |
A comprehension that is one of several arguments of a call makes the call hard to read. Give it a name on the line above, and pass the name.
def points(cache, days): return pd.concat([pd.read_parquet(cache / f"{day}.parquet") for day in days], ignore_index=True) frames = [pd.read_parquet(cache / f"{day}.parquet") for day in days] return pd.concat(frames, ignore_index=True)What the rule reports
Section titled “What the rule reports”The rule reports a comprehension or generator expression that is one of several arguments of a
call. It leaves a comprehension alone that is the only argument, as in sum(x.cost for x in items).
How to fix it
Section titled “How to fix it”Inside a function, xpd can bind a call argument above a return, assignment, or standalone call. It saves the callable first and captures earlier arguments when moving the comprehension could change their values. Calls with unpacked arguments and comprehensions inside conditional expressions 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 call holds a loop, and a reader has to find where the loop ends before the other arguments make sense. The name on the line above says what the loop builds, and the call then fits on one short line.
Diagnostic message
Section titled “Diagnostic message”This comprehension is one of several arguments of a call. Give it a name on the line above, and pass the name.See all rules in the Python pack.