Why is there no __iter__() for lists strings and tuples?

Walter Moreira walterm at parque.homelinux.net
Sat Dec 21 21:43:31 EST 2002


On Sat, Dec 21, 2002 at 03:45:30AM -0500, Oren Tirosh wrote:
> for i in a:
>    do_somewith_with(i)
> 
> is equivalent in Python < 2.2 to:
> 
> _tmpidx = 0
> try:
>     while 1:
>         i = a[_tmpidx]
>         _tmpidx = _tmpidx +1
>         do_somewith_with(i)
> except IndexError:
>     pass
> 
> 
> and in Python >= 2.2:
> 
> if hasattr(a, '__iter__'):
>     _tmpiter = a.__iter__()
>     try:
>         while 1:
>             i = _tmpiter.next()
>             do_something_with(i)
>     except StopIteration:
>         pass
> else:
>     # fall back to < 2.2 behavior


Sometime ago I also thought that this was the equivalence with the 'for'
loop.  But if you do:

    >>> for i in [1,2,3]:
    ...     raise StopIteration
    ...
    Traceback (most recent call last):
      File "<stdin>", line 2, in ?
    StopIteration
    >>>

So, it is not completely equivalent. I expected the StopIteration to
finalize the 'for' loop.  On the other hand, if the exception is raised
from the iterator, the loop ends.  Why does this asymmetric behavior
ocurr?

(I should use the source, I know... :-)

Walter




More information about the Python-list mailing list