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

后端 未结 5 851
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-31 07:46

I have a generator function that goes something like this:

def mygenerator():
    next_value = compute_first_value() # Costly operation
    while next_value          


        
5条回答
  •  温柔的废话
    2020-12-31 08:44

    I needed something similar. This is what I landed on. Push the generator function into an inner and return it's call.

    def mygenerator():
        next_value = compute_first_value()
    
        def generator():
            while next_value != terminating_value:
                yield next_value
                next_value = compute_next(next_value)
    
        return generator()
    

提交回复
热议问题