On 2009-02-10, Albert Hopkins <mar...@letterboxes.org> wrote: > On Tue, 2009-02-10 at 12:50 -0800, Josh Dukes wrote: > > I don't understand what you mean by this. But if you really want to > know if a generator is "non-empty": > > def non_empty(virgin_generator): > try: > virgin_generator.next() # note you just lost the first value > return True > except StopIteration: > return False > > The only way to get around this is to put all the values of a generator > inside a container (e.g. a list): > > l = list(generator_object) > > but in doing so you've (obviously) lost the advantages of the generator.
Well he could always use a wrapper like the following: nothing = object() class BoolIterator (object): def __init__(self, iter): self.iter = iter self.value = nothing self.item = nothing def __iter__(self): return (self) def __nonzero__(self): if self.value is nothing: try: self.item = self.iter.next() self.value = True return True except StopIteration: self.value = False return False else: return self.value def next(self): if self.item is not nothing: result = self.item self.item = nothing return result if self.value is not nothing: return self.iter.next() else: try: result = self.iter.next() self.value = True return result except StopIteration: self.value = False raise it1 = BoolIterator(i for i in xrange(10)) for i in it1: print i it2 = BoolIterator(i for i in xrange(10)) if it2: print "item found" for i in it2: print i else: print "problem" it3 = BoolIterator(i for i in xrange(0)) if it3: print "problem" else: print "it3 is empty" -- http://mail.python.org/mailman/listinfo/python-list