question about True values
pavlovevidence at gmail.com
Fri Oct 27 04:46:36 CEST 2006
Ben Finney wrote:
> Gabriel Genellina <gagsl-py at yahoo.com.ar> writes:
> > At Wednesday 25/10/2006 23:29, Paul Rubin wrote:
> > >Steve Holden <steve at holdenweb.com> writes:
> > >I get that iter(()) is True (Python 2.3.4).
> > It's False on 2.4.2 - and perhaps it's what one would expect, but
> > since this behavior is not documented anywhere, one should not count
> > on it.
Good advice, because on 2.5 it's True again.
> Doesn't this fall under "any empty sequence" in the following list of
Nope. 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. So even in 2.4.3 some "empty" iterators return True:
>>> a = 
>>> bool(x for x in a)
The only reasonable advice is to avoid the direct boolean test ("if
a:") altogether if you want to support iterators.
Unfortunately, iterators and lists have a lot of overlapping use, and
it's very common to test for emptiness of lists using "if a:". If one
tries to use an iterator where a list is expected it could lead to a
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. Objects of
these types should raise exceptions when used as a boolen. numpy
arrays wisely already do this.
(I'll stop short of mentioning that, because neither numpy arrays nor
iterators consider "empty" to be "false", the idea that "empty" is
"false" is very far from self-evident; therefore lists, tuples, dicts,
and sets should also raise exceptions when used as a boolean. I won't
mention that, though.)
More information about the Python-list