Hello, On Thu, Oct 21, 2010 at 12:26:50PM +0000, Steven D'Aprano wrote: > I know what you're thinking: "it's easy to cache > the next result, and return it on the next > call". But iterators can also be dependent on > the time that they are called, like in this > example: > > def evening_time(): > while 1: > yield time.strftime("%H:%m") # e.g. "23:20"
When working with things like this you should anyway use some lock/sync/transaction, so that prefetching iterator will most probably be OK unless you've fundamentally screwed your code's logics. WRT the prefetcher, I'd use smth like this: > def rand_gen(): > x = random.random() > while x < 0.9: > yield x > x = random.random() > > class prefetcher: > def __init__(self, i): > self.i = i > self.s = False > self._prefetch() > def _prefetch(self): > try: self.n = self.i.next() > except StopIteration: self.s = True > def has_next(self): return not self.s > def next(self): > if self.s: raise StopIteration() > else: > n = self.n > self._prefetch() > return n > def __iter__(self): return self > > rand_pre = prefetcher(rand_gen()) > while rand_pre.has_next(): print rand_pre.next() -- With best regards, xrgtn -- http://mail.python.org/mailman/listinfo/python-list