Skip to content

Instantly share code, notes, and snippets.

@takluyver
Created January 14, 2016 22:12
Show Gist options
  • Save takluyver/8cc2138018be0e074bc4 to your computer and use it in GitHub Desktop.
Save takluyver/8cc2138018be0e074bc4 to your computer and use it in GitHub Desktop.
Wrap a generator in a re-usable iterator
class CursorIterator(object):
def __init__(self, sequence, start=0):
self.sequence = sequence
self.position = start - 1
def __next__(self):
self.position += 1
return self.sequence[self.position]
class RepeatableIterable(object):
def __init__(self, iterator):
self.iterator = iterator
self.cache = []
def __iter__(self):
return CursorIterator(self)
def __getitem__(self, i):
while i >= len(self.cache):
self.cache.append(next(self.iterator))
return self.cache[i]
def gen():
for a in range(10):
yield a
g = gen()
print('gen 1st time:', list(g))
print('gen 2nd time:', list(g))
g2 = RepeatableIterable(gen())
print('wrapped gen 1st time:', list(g2))
print('wrapped gen 2nd time:', list(g2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment