question about True values
Carl Banks
pavlovevidence at gmail.com
Thu Oct 26 22:46:36 EDT 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
> evaluates-to-false:
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)
True
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
silent failure.
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.)
Carl Banks
More information about the Python-list
mailing list