Skip to content

Instantly share code, notes, and snippets.

@JakeTheCorn
Last active July 31, 2020 14:15
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 JakeTheCorn/ea0fe5d550c34761a7966f579042c162 to your computer and use it in GitHub Desktop.
Save JakeTheCorn/ea0fe5d550c34761a7966f579042c162 to your computer and use it in GitHub Desktop.
Leaving this for my own record. how to implement a lazy eval loop in python
import unittest
class Container:
def __init__(self, items):
self.__cur = 0
self.__items = items
def __iter__(self):
self.__cur = 0
return self
def next(self):
if self.__cur + 1 > len(self.__items):
raise StopIteration
self.__cur += 1
return '%s * 2' % self.__items[self.__cur - 1]
class Test(unittest.TestCase):
def test(self):
container = Container([0, 1])
for idx, item in enumerate(container):
self.assertEqual(item, '%s * 2' % idx)
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment