4

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 Answers2

3

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
cs95
  • 379,657
  • 97
  • 704
  • 746
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
3

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]
cs95
  • 379,657
  • 97
  • 704
  • 746
  • what do you mean by * in (*range(3), *generatorA()) – Balakrishnan Sathiyakugan Nov 09 '18 at 11:02
  • What if the generator is a call back function . Than I don't know when it will execute ? Don't we – Balakrishnan Sathiyakugan Nov 09 '18 at 11:03
  • @BalakrishnanSathiyakugan that's the syntax for iterable unpacking. Also, what do you mean by call back in this context and why would it matter? – cs95 Nov 09 '18 at 11:26
  • I am using keras call back function to get the accuracy and losses for every ephos. so I update it in to the front end using yield and ajax call. – Balakrishnan Sathiyakugan Nov 09 '18 at 11:29
  • @BalakrishnanSathiyakugan In that case you might want to look at [`asyncio`](https://docs.python.org/3/library/asyncio.html). – cs95 Nov 09 '18 at 11:41
  • I am doing a web app , when the button is clicked newly updated data will be trained. When the training is on progress, I should show the progress on the the front end. Progress means for every epoch I should show the accuracy and error level. I could easily get it from keras call back functions "on_epoch_end " but the call back has no return method because it's executing only on the model training. – Balakrishnan Sathiyakugan Nov 09 '18 at 12:56