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

Carl Banks pavlovevidence at gmail.com
Thu Oct 26 23:50:20 EDT 2006


Robert Kern wrote:
> Ben Finney wrote:
>
> > 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.
>
> And indeed, they are already allowed to do so.
>
> Python 2.4.1 (#2, Mar 31 2005, 00:05:10)
> Type "copyright", "credits" or "license" for more information.
>
> In [1]: len(iter(()))
> Out[1]: 0
>
> In [2]: bool(iter(()))
> Out[2]: False

And indeed, the built-in iterators have already backed away from this
idea.

Python 2.5c2 (r25c2:51859, Sep 13 2006, 09:50:32)
[GCC 4.1.2 20060814 (prerelease) (Debian 4.1.1-11)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> len(iter(()))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object of type 'tupleiterator' has no len()
>>> bool(iter(()))
True


Carl Banks




More information about the Python-list mailing list