Created
July 11, 2014 03:57
-
-
Save hahastudio/86d537daea702f9766ab to your computer and use it in GitHub Desktop.
def next() for Python pre-2.6 from http://stackoverflow.com/questions/1716428/def-next-for-python-pre-2-6-instead-of-object-next-method
This file contains hidden or 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
# 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