[Python-ideas] Fwd: Fwd: unpacking generalisations for list comprehension
Steven D'Aprano
steve at pearwood.info
Sat Oct 15 04:18:21 EDT 2016
On Fri, Oct 14, 2016 at 07:51:18AM +0000, Neil Girdhar wrote:
> Here's an interesting idea regarding yield **x:
>
> Right now a function containing any yield returns a generator. Therefore,
> it works like a generator expression, which is the lazy version of a list
> display. lists can only contain elements x and unpackings *x. Therefore,
> it would make sense to only have "yield x" and "yield *xs" (currently
> spelled "yield from xs")
No, there's no "therefore" about it. "yield from x" is not the same as
"yield *x".
*x is conceptually equivalent to replacing "*x" with a
comma-separated sequence of individual items from x.
Given x = (1, 2, 3):
f(*x) is like f(1, 2, 3)
[100, 200, *x, 300] is like [100, 200, 1, 2, 3, 300]
a, b, c, d = 100, *x is like a, b, c, d = 100, 1, 2, 3
Now replace "yield *x" with "yield 1, 2, 3". Conveniently, that syntax
already works:
py> def gen():
... yield 1, 2, 3
...
py> it = gen()
py> next(it)
(1, 2, 3)
"yield *x" should not be the same as "yield from x". Yielding a starred
expression currently isn't allowed, but if it were allowed, it would be
pointless: it would be the same as unpacking x, then repacking it into a
tuple.
Either that, or we would have yet another special meaning for *
unrelated to the existing meanings.
--
Steve
More information about the Python-ideas
mailing list