Alternative iterator syntax

Ben Wolfson wolfson at midway.uchicago.edu
Wed Feb 21 16:51:15 EST 2001


In article <OyVk6.349$a_2.40263 at news1.rdc1.az.home.com>,
Tim Hochberg <tim.hochberg at ieee.org> wrote:
>
>"Michael Hudson" <mwh21 at cam.ac.uk> wrote in message
>news:m31ysru8ws.fsf at atrus.jesus.cam.ac.uk...
>> "Tim Hochberg" <tim.hochberg at ieee.org> writes:
>>
>> [schnipp]
>> > I don't think this will work right though. Consider:
>> >
>> > for k in aUserDict.keys:
>> >    # Do some stuff
>> > for k in aUserDict.keys:
>> >     # Do some more stuff
>> >
>> > The way this is implemented here the second loop would bail out
>> > immediately because there is only a single iterator for a given
>> > instance and it is already exhausted.
>>
>> Nah, reset the allocator every time item 0 is asked for.  I'd have to
>> admit I haven't read Huaiyu Zhu's proposal carefully enough to be sure
>> this would work, but something like this ought to be possible, I'd
>> have thought.
>
>But the loop psuedocode that Huaiyu Zhu proposed has no concept of asking
>for item zero:
>
>   for a, b, c, ... in A:
>        do something
>
>becomes:
>
>    while 1:
>        try:
>            a, b, c, ... = A.__next__()
>            do something
>        except IndexError:
>            break
>
>One could add an A.__reset__() call to the start of the loop, but I think
>that that would hamstring some other applications one would like for
>iterators. Resetting at the end doesn't appear to be any better. For the
>moment, I'll stand my original claim that the The Right Thing To Do (tm) is
>to get a new iterator each time.

One could also specify that, when appropriate, an iterator calls
__reset__ before raising an IndexError.

-- 
Barnabas T. Rumjuggler
For the world, I count it not an inn, but an hospital; and a place not to
live, but to die in.
 -- Thomas Browne, _Religio Medici_



More information about the Python-list mailing list