Skip to content

Instantly share code, notes, and snippets.

@baoilleach
Created June 27, 2019 13:21
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 baoilleach/6678490ea3928c9a59eed4fafd6b2520 to your computer and use it in GitHub Desktop.
Save baoilleach/6678490ea3928c9a59eed4fafd6b2520 to your computer and use it in GitHub Desktop.
A peekable Python iterator
class Peekable:
def __init__(self, it):
self.it = it
self.finished = False
self.curr = None
self.nextval = next(it)
def __iter__(self):
return self
def __next__(self):
if self.finished:
raise StopIteratoin
curr = self.nextval
try:
self.nextval = next(self.it)
except StopIteration:
self.finished = True
return curr
def peek(self):
if self.finished:
return None
return self.nextval
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment