I yould like to have generators that defer to other generators, e.g.
def gx():
for i in [1, 2, 3]:
yield i
def gy():
for i in [11, 12, 13]:
yield i
def gz():
"""this should defer to gx and gy to
generate [1, 2, 3, 11, 12, 13]"""
for i in gx(): yield i
for i in gy(): yield i
Is the explicit loop in gz() the only way to do this, or are there better alternatives?
In currently released Python versions, an explicit loop is the only way to invoke sub-generators. (I presume your example is just, well, an example -- not the exact problem you want to solve.)
Python 3.3 will add the special syntax yield from
for this purpose:
def gz():
"""this should defer to gx and gy to
generate [1, 2, 3, 11, 12, 13]"""
yield from gx()
yield from gy()
See PEP 380 for further details.
Using itertools.chain
:
import itertools
gz = itertools.chain(gx(), gy())
In the documentation of chain
they describe it by implementation:
def chain(*iterables):
for it in iterables:
for element in it:
yield element
You can draw inspiration from this as well :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With