Created
July 31, 2020 14:55
-
-
Save alaniwi/7b819b7b34a76af5fe59b77676cbbd66 to your computer and use it in GitHub Desktop.
iterator with `at_end` property
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 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