Skip to content

Instantly share code, notes, and snippets.

@atdt
Created December 29, 2011 04:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atdt/1531981 to your computer and use it in GitHub Desktop.
Save atdt/1531981 to your computer and use it in GitHub Desktop.
peekable iterator
# using a tuple for self.buf was the fastest out of handful of
# different implementations I played around with.
class peekable(object):
def __init__(self, iterable):
"""
Extends iterators with a `peek` method that returns the next element
that the iterator will yield. Raises StopIteration if there is no next
element.
>>> iterator = peekable(range(10))
>>> while True:
... try:
... assert iterator.peek() == next(iterator)
... except StopIteration:
... break
...
"""
self.iter = iter(iterable)
self.buf = ()
def peek(self):
if not self.buf:
self.buf = (next(self.iter),)
return self.buf[0]
def __iter__(self):
return self
def __next__(self):
if self.buf:
val = self.buf[0]
self.buf = ()
return val
return next(self.iter)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment