Skip to content

Instantly share code, notes, and snippets.

@alaniwi
Created July 31, 2020 14:55
Show Gist options
  • Save alaniwi/7b819b7b34a76af5fe59b77676cbbd66 to your computer and use it in GitHub Desktop.
Save alaniwi/7b819b7b34a76af5fe59b77676cbbd66 to your computer and use it in GitHub Desktop.
iterator with `at_end` property
class MyIter:
def __init__(self, iterable):
self._iterator = iter(iterable)
self.at_end = False
self._prefetch_next()
def __next__(self):
if self.at_end:
raise StopIteration
next_one = self.next_one
self._prefetch_next()
return next_one
def _prefetch_next(self):
try:
self.next_one = next(self._iterator)
except StopIteration:
del self.next_one
self.at_end = True
def __iter__(self):
return self
if __name__ == '__main__':
vals = MyIter(range(3))
for x in vals:
print(x, vals.at_end)
# PRINTS
# 0 False
# 1 False
# 2 True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment