Python - is there any way to organize a group of yields in sub function to yield outside the main function?
If you're using the latest and greatest python
(>= 3.3), there's the yield from
construct.
yield from funB()
It does exactly what you want: you can invoke a function as a sub-generator, and yield back everything it yields to you.
If you're using an earlier version of python
, then I'm afraid you'll have to do it manually:
for x in funB(): yield x
You can group them like this, to save up space:
funs = [funA, funB, funC]
for fun in funs:
for item in fun():
yield item
itertools.chain
is the function you're looking for
import itertools
def funA():
for x in range(10):
yield x
def funB():
for x in range(10,20):
yield x
def funC():
for x in range(20,30):
yield x
def funs():
for x in itertools.chain(funA(), funB(), funC()):
yield x
print [x for x in funs()]
Outputs:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]