Pre-PEP: Unpacking in Comprehensions

That’s the intention, yes. I can add some words to that effect to the PEP.

That’s a good point. It may take a little while to find the right specific words to add to the PEP, but I can give the short version of my personal reasoning here, which is that if we’re expanding the definition of what a generator expression is, then the way to remain consistent with Python’s existing behavior (where f(x for x in it) passes a single argument to f) would be for f(*x for x in it) to be equivalent to f((*x for x in it)). That is, it seems to me like f(<some valid generator expression>) should always pass that generator as a single argument.

Further unpacking that generator to separate arguments to f could still be accomplished with f(*(*x for x in it)), which is perhaps a little clunky but is, I think, the way to remain consistent with what we already have.

A little bit of support in this direction, perhaps, comes from the way that the syntax error for f(*x for x in it) is reported in 3.13, which suggests that this is interpreted as f(<a single malformed generator expression>) rather than as f(*<something>):

>>> f(*x for x in its)
  File "<python-input-0>", line 1
    f(*x for x in its)
      ^^
SyntaxError: iterable unpacking cannot be used in comprehension
3 Likes