Boolean value of generators

Carl Banks pavlovevidence at gmail.com
Thu Oct 14 19:40:58 CEST 2010


On Oct 14, 2:16 am, Tony <ton... at ximera.net> 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?

In general, the only way to test if a generator is empty is to try to
consume an item.  (It's possible to write an iterator that consumes an
item and caches it to be returned on the next next(), and whose
boolean status indicates if there's an item left.  I would guess the
recipe Peter Otten pointed you to does that.)

The unfortunate thing about this is that functions written to iterate
over sequences that test if the sequence is empty with a boolean test
cannot be used with generators, and will fail silently.  This hurts
duck typing.

This became an issue some releases ago (2.4, I think) when someone
decided duck typing was a good thing and so it would be a good idea if
iterators that did know if they were empty had a boolean status
indicating as such.  GvR angrily told them to change it back next
release.  I have to agree with GvR here: at least this way there is a
simple rule whether boolean test works.  (Sequences return boolean
status indicating if they're empty; other iterators return True.)  The
better thing would be if boolean wasn't used to test for emptiness at
all; the whole concept of booleans in Python is overloaded and that
hurts duck typing.



Carl Banks



More information about the Python-list mailing list