I have a generator function that goes something like this:
def mygenerator():
next_value = compute_first_value() # Costly operation
while next_value != terminating_value:
yield next_value
next_value = compute_next_value()
I would like the initialization step (before the while loop) to run as soon as the function is called, rather than only when the generator is first used. What is a good way to do this?
I want to do this because the generator will be running in a separate thread (or process, or whatever multiprocessing uses) and I won't be using the return for a short while, and the initialization is somewhat costly, so I would like it to do the initialization while I'm getting ready to use the values.
You can create a "preprimed" iterator fairly easily by using
itertools.chain
:I needed something similar. This is what I landed on. Push the generator function into an inner and return it's call.
I suppose you can yield None after that first statement is completed, then in your calling code:
For my use case I used a modified version of @ncoghlan answer but wrapped in a factory function to decorate the generating function:
Then just decorate the function:
and the first value will be calculated immediately, and the result is transparent.