Is it possible to nest yield from
statements?
The simple form is obvious:
def try_yield1():
x = range(3)
yield from x
Which produces:
0
1
2
But what if I have nested generators?
def try_yield_nested():
x = [range(3) for _ in range(4)]
yield from ((yield from y) for y in x)
This produces:
0
1
2
None # why?
0
1
2
None # ...
0
1
2
None # ...
Why does it produce None
if I used yield from
(even though it is nested)?
I know I can do something like:
from itertools import chain
def try_yield_nested_alternative():
x = [range(3) for _ in range(4)]
yield from chain.from_iterable(x)
Which produces the same output leaving out the None
(which is what I expect). I can also write a simple loop:
for x in [range(3) for _ in range(3)]:
yield from x
But, I thought it would be more pythonic to use nested delegation (preferably even yield from x from y
or yield from x for x in y
, but that is not proper syntax). Why is it not working as I expect?