Created
May 24, 2012 16:59
-
-
Save mattspitz/2782794 to your computer and use it in GitHub Desktop.
Empty iterator check
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
""" | |
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