Skip to content

Instantly share code, notes, and snippets.

@sfkleach
Created January 12, 2023 13:52
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 sfkleach/25cef93211abf139fd9dd6759cc98c9c to your computer and use it in GitHub Desktop.
Save sfkleach/25cef93211abf139fd9dd6759cc98c9c to your computer and use it in GitHub Desktop.
Convert an iterator to a pushable iterator
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