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

后端 未结 5 854
爱一瞬间的悲伤
爱一瞬间的悲伤 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:28

    You can create a "preprimed" iterator fairly easily by using itertools.chain:

    from itertools import chain
    
    def primed(iterable):
        """Preprimes an iterator so the first value is calculated immediately
           but not returned until the first iteration
        """
        itr = iter(iterable)
        try:
            first = next(itr)  # itr.next() in Python 2
        except StopIteration:
            return itr
        return chain([first], itr)
    
    >>> def g():
    ...     for i in range(5):
    ...         print("Next called")
    ...         yield i
    ...
    >>> x = primed(g())
    Next called
    >>> for i in x: print(i)
    ...
    0
    Next called
    1
    Next called
    2
    Next called
    3
    Next called
    4
    

提交回复
热议问题