Skip to content

Instantly share code, notes, and snippets.

@Garciat
Last active August 29, 2015 14:05
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 Garciat/b59e7522b9909d1a21bc to your computer and use it in GitHub Desktop.
Save Garciat/b59e7522b9909d1a21bc to your computer and use it in GitHub Desktop.
# iterable class
class naturals(object):
def __init__(self, top):
assert top >= 1, 'top >= 1'
self._cur = 1
self._top = top
def __iter__(self):
return self
def __next__(self):
if self._cur > self._top:
raise StopIteration()
tmp = self._cur
self._cur += 1
return tmp
# generator function
def naturals(top):
n = 1
while n <= top:
# `yield x` puts the value `x` on hold, and halts function execution.
# the result is a generator object, which follows the iterator pattern.
# calling next() on one of these will return `x` and resume function
# execution, until another `yield` statement is found or the function ends
yield n
n += 1
# for-in iteration
for n in naturals(10):
print(n)
# manual iteration (naive, imho)
it = naturals(10)
try:
while True:
n = next(it)
print (n)
except StopIteration:
pass
# manual iteration (generic)
nums = naturals(10)
it = iter(nums) # make sure we are dealing with an iterator object
sentinel = object() # create unique object
while True:
n = next(it, sentinel) # next returns sentinel instead of raising exception
if n is sentinel:
break
print(n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment