Last active
September 16, 2021 20:03
-
-
Save alexander-bauer/c8672550d6b98ed2ecad to your computer and use it in GitHub Desktop.
Peekable iterator wrapper in Python3
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(): | |
"""An iterable class which can return the next element of the wrapped | |
iterator without advancing it.""" | |
def __init__(self, iterator): | |
self.iterator = iterator | |
self.peeked = False | |
def peek(self): | |
if not self.peeked: | |
self.peeked = True | |
self.head = next(iterator) | |
return self.head | |
def __next__(self): | |
if self.peeked: | |
self.peeked = False | |
return self.head | |
else: | |
return next(iterator) |
mahmoudimus
commented
Sep 16, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment