Boolean value of generators

Peter Otten __peter__ at
Thu Oct 14 15:36:15 CEST 2010

Tony wrote:

> I have been using generators for the first time and wanted to check for
> an empty result.  Naively I assumed that generators would give
> appopriate boolean values.  For example
> def xx():
>   l = []
>   for x in l:
>     yield x
> y = xx()
> bool(y)
> I expected the last line to return False but it actually returns True.
> Is there anyway I can enhance my generator or iterator to have the
> desired effect?

* What would you expect 

def f():
    if random.randrange(2):
        yield 42

print bool(f())

to print? Schrödinger's Cat?

* You can wrap your generator into an object that reads one item in advance. 
A slightly overengineered example:

* I would recommend that you avoid the above approach. Pythonic solutions 
favour EAFP ( over look-

    value = next(y)
except StopIteration:
    print "ran out of values"


value = next(y, default)


More information about the Python-list mailing list