Truth value of iterators [was: question about True values)

Ben Finney bignose+hates-spam at
Fri Oct 27 04:58:42 CEST 2006

"Carl Banks" <pavlovevidence at> writes:

> An iterator is not a sequence, and it's impossible to determine
> whether an iterator is "empty" in general, except by trying to get
> an item from it. [...]
> IMO, this is big time wart in the language.  Iterators have no
> calculatable truth value; for many other types a truth value doesn't
> make sense (for instance: function objects, type objects, modules,
> user-defined types that don't bother with __nonzero__).  Using such
> objects in a boolean context is almost always an error.

It still seems like a reasonable thing for a programmer to do though,
even if the language doesn't currently support it.

Would it make sense to *define* a truth value for iterators? Or at
least to enable those that *are* able to say "I'm empty" to do so in a
way that boolean contexts can interpret as "false"?

Perhaps allowing (but not requiring) an iterator object to grow a
'len' method is the simplest way.

 \      "I like my dental hygenist, I think she's very pretty; so when |
  `\    I go to have my teeth cleaned, while I'm in the waiting room I |
_o__)                 eat an entire box of cookies."  -- Steven Wright |
Ben Finney

More information about the Python-list mailing list