I have a generator function that goes something like this:
def mygenerator():
next_value = compute_first_value() # Costly operation
while next_value
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