Boolean value of generators
Peter Otten
__peter__ at web.de
Thu Oct 14 09:36:15 EDT 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:
http://code.activestate.com/recipes/577361-peek-ahead-an-iterator/
* I would recommend that you avoid the above approach. Pythonic solutions
favour EAFP (http://docs.python.org/glossary.html#term-eafp) over look-
before-you-leap:
try:
value = next(y)
except StopIteration:
print "ran out of values"
else:
do_something_with(value)
or
value = next(y, default)
Peter
More information about the Python-list
mailing list