Include the yield inside another function

Viewed 561

I have two functions , generatorA() calls the generatorB() inside it. I want to get all the yield when calling the generatorB(), but I only get 0,1,2 how to get 0,1,2,3,4,5

generatorA() is a call back function. so I can't say, when It will be called.

def generatorA():
    mylist = range(4,6)
    for i in mylist:
        yield i


def generatorB():
    generatorA()

    mylist = range(3)
    for i in mylist:
        yield i

for i in generatorB():
    print(i)
2 Answers

Use yield from:

def generatorA():
    return range(4,6)  

def generatorB():
    mylist = range(3)
    for i in mylist:
        yield i

    yield from generatorA()

for i in generatorB():
    print(i)

Output

0
1
2
4
5

Use yield from, and you can further shorten this with iterable unpacking.

def generatorB():
    yield from (*range(3), *generatorA())

You could do the same thing to generatorA:

def generatorA():
    yield from range(4,6)

(...But I assume that generatorA is a stand-in for something more complex.)

>>> list(create())
[0, 1, 2, 4, 5]
Related