Skip to content

Instantly share code, notes, and snippets.

@hahastudio
Created July 11, 2014 03:57
Show Gist options
  • Save hahastudio/86d537daea702f9766ab to your computer and use it in GitHub Desktop.
Save hahastudio/86d537daea702f9766ab to your computer and use it in GitHub Desktop.
# def next() for Python pre-2.6
class Throw(object): pass
throw = Throw() # easy sentinel hack
def next(iterator, default=throw):
"""next(iterator[, default])
Return the next item from the iterator. If default is given
and the iterator is exhausted, it is returned instead of
raising StopIteration.
"""
try:
iternext = iterator.next.__call__
# this way an AttributeError while executing next() isn't hidden
# (2.6 does this too)
except AttributeError:
raise TypeError("%s object is not an iterator" % type(iterator).__name__)
try:
return iternext()
except StopIteration:
if default is throw:
raise
return default
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment