Created
June 27, 2019 13:21
-
-
Save baoilleach/6678490ea3928c9a59eed4fafd6b2520 to your computer and use it in GitHub Desktop.
A peekable Python iterator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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