[Python-Dev] Tricky way of of creating a generator via a comprehension expression

Greg Ewing greg.ewing at canterbury.ac.nz
Wed Nov 22 17:14:41 EST 2017

Ivan Levkivskyi wrote:
> while `g = list((yield i) for i in range(3))` is defined as this code:
>     def __gen():
>        for i in range(3):
>          yield (yield i)
>     g = list(__gen())

Since this is almost certainly not what was intended, I think that
'yield' inside a generator expression should simply be disallowed.

The problem with making it work intuitively is that there's no way
to distinguish between the implicit yields producing values for the
generator comprehension and the explicit ones that the programmer
is expecting to be passed through and yielded from the enclosing
generator function.

Fixing that would require adding another whole layer of complexity
similar to what Yuri did to support async generators, and I can't
see that being worth the effort.


More information about the Python-Dev mailing list