Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I run the initialization code for a generator function immediately, rather than at the first call?

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.

like image 347
Ryan C. Thompson Avatar asked Apr 19 '11 23:04

Ryan C. Thompson


1 Answers

class mygenerator(object):
    def __init__(self):
        next_value = compute_first_value()
    def __iter__(self):
        return self
    def next(self):
        if next_value == terminating_value:
            raise StopIteration()
        return next_value
like image 177
Andrey Sboev Avatar answered Oct 15 '22 03:10

Andrey Sboev