Boolean value of generators
__peter__ at web.de
Thu Oct 14 15:36:15 CEST 2010
> 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()
> 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
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 (http://docs.python.org/glossary.html#term-eafp) over look-
value = next(y)
print "ran out of values"
value = next(y, default)
More information about the Python-list