Skip to content

Instantly share code, notes, and snippets.

@tdavis
Created December 1, 2009 21:14
Show Gist options
  • Select an option

  • Save tdavis/246654 to your computer and use it in GitHub Desktop.

Select an option

Save tdavis/246654 to your computer and use it in GitHub Desktop.
def foo(size, default=0, existing=None):
"""
Yield values to a certain size, using an existing value at the same
index or the default value, in that order.
>>> f = foo(1)
>>> f.next()
0
>>> f.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> f = foo(2, 'bar', (5,))
>>> f.next()
5
>>> f.next()
'bar'
"""
existing = existing or []
for x in range(size):
try:
yield existing[x]
except IndexError:
yield default
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment