Skip to content

Instantly share code, notes, and snippets.

@mattspitz
Created May 24, 2012 16:59
Show Gist options
  • Save mattspitz/2782794 to your computer and use it in GitHub Desktop.
Save mattspitz/2782794 to your computer and use it in GitHub Desktop.
Empty iterator check
"""
This is useful to avoid throwing empty iterators into a gevent Pool's imap() function, which hangs on empty input.
has_next, maybe_it = iterator_has_next(my_iterator)
if has_next:
use_the_iterator(maybe_it)
else:
handle_empty_iterator()
"""
def iterator_has_next(it):
""" Returns (boolean, iterator?), where iterator is the iterator itself if it has at least one element. """
try:
val = it.next()
except StopIteration:
return False, None
def new_it():
yield val
for v in it:
yield v
return True, new_it()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment