I understand that this post is 5 years old, but I found it, looking for an idiomatic way to do this, and did not see how my solution was published. So for posterity:
import itertools def get_generator(): """ Returns (bool, generator) where bool is true iff the generator is not empty. """ gen = (i for i in [0, 1, 2, 3, 4]) a, b = itertools.tee(gen) try: a.next() except StopIteration: return (False, b) return (True, b)
Of course, as I am sure, many commentators will point out that these are hacks and only work in certain limited situations (for example, when the generators are free from side effects). YMMV.
Real John Connor Mar 23 '14 at 17:02 2014-03-23 ββ17:02
source share