Skip to content

python/comprehension-multi-line

Pack Severity Fix Versions
Python warning unsafe, with xpd check --fix --unsafe-fixes All versions

A comprehension that runs over more than one line is hard to read. Write a loop, or give the expression for one item a name and a function.

def stacks(trades):
return {
str(lot): Stack(group["spread"].to_numpy(), group["mw"].cumsum().to_numpy())
for lot, group in trades.groupby("lot", sort=False)
}
found = {}
for lot, group in trades.groupby("lot", sort=False):
spread = group["spread"].to_numpy()
depth = group["mw"].cumsum().to_numpy()
found[str(lot)] = Stack(spread, depth)
return found

The rule reports a comprehension or generator expression that runs over more than one line.

Inside a function, xpd can turn a list or dict comprehension into a loop in a return, an assignment, or a call argument. It can build into a fresh assignment target directly. When an exception could expose a partial result, it builds the collection separately before assigning it. The loop uses a fresh variable if its original name is used elsewhere in the function.

Apply the fix with xpd check --fix --unsafe-fixes. The additional locals and the lifetime of their values are observable.

A comprehension that needs several lines holds more than one step, and its result stands before the loop that makes it, so a reader goes through it twice. The loop gives each step its own line and its own name, in the order it runs.

This comprehension runs over more than one line. Write a loop, or give the expression for one item a name and a function.

See all rules in the Python pack.