Created
January 12, 2023 13:52
-
-
Save sfkleach/25cef93211abf139fd9dd6759cc98c9c to your computer and use it in GitHub Desktop.
Convert an iterator to a pushable 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 Pushable: | |
def __init__(self, iter): | |
self.source = iter | |
self.stored = [] | |
def __iter__(self): | |
return self | |
def __bool__(self): | |
if self.stored: | |
return True | |
try: | |
self.stored.append(next(self.source)) | |
except StopIteration: | |
return False | |
return True | |
def push(self, value): | |
self.stored.append(value) | |
def peek(self): | |
if self.stored: | |
return self.stored[-1] | |
value = next(self.source) | |
self.stored.append(value) | |
return value | |
def __next__(self): | |
if self.stored: | |
return self.stored.pop() | |
return next(self.source) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment