Pre-PEP: Unpacking in Comprehensions

I’ve always found it surprising and counter-intuitive that unpacking in comprehensions doesn’t work ever since I learned about generalized unpacking in container literals.

That said, I think the PEP needs to address the concern raised by the explanations to why such a feature wasn’t included in PEP-448, specifically that it would cause ambiguity when unpacking in an unbracketed generator expression in a call since argument list already supports unpacking.

That is, which one of these is intended?

f(*x for x in it) == f((*x for x in it))

or:

f(*x for x in it) == f(*(x for x in it))

Original quote from PEP-448:

Unbracketed comprehensions in function calls, such as f(x for x in it), are already valid. These could be extended to:

f(*x for x in it) == f((*x for x in it))
f(**x for x in it) == f({**x for x in it})

However, it wasn’t clear if this was the best behaviour or if it should unpack into the arguments of the call to f. Since this is likely to be confusing and is of only very marginal utility, it is not included in this PEP. Instead, these will throw a SyntaxError and comprehensions with explicit brackets should be used instead.

5 Likes