Alternative iterator syntax

Tim Hochberg tim.hochberg at ieee.org
Wed Feb 21 15:29:34 EST 2001


"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.

On the other hand (it was a short moment), this isn't really the behaviour
you want for, for instance,  file.readlines. Let's look at two cases:

One would like aDict.keys to return distinct iterators:

for key in aDict.keys:
  doSomething
for key in aDict.keys:
  doSomething

This should iterate over aDict's keys twice.

However aFile can really have one iterator:

for line in aFile.readlines:
    doSomething
for line in aFile.readlines:
    doSomething

This should almost certainly only iterate over the file once (in the first
loop) and bail out immediately in the second loop. I suppose allowing
different types of objects to return new iterators or not as appropriate
would fix this.

OK, so my new position is that objects should return new iterators when they
feel it's appropriate <0.1 wink>

Not-really-concerned-that-I'll-be-mistaken-for-the-real-tim'ly yours,

-tim

> I mean,
>
> l = range(10)
> for i in l:
>    # do some stuff
> for i in l:
>    # do some other stuff
>
> will have to do something along these lines, no?
>
> Cheers,
> M.
>
> --
>   In general, I'd recommend injecting LSD directly into your temples,
>   Syd-Barret-style, before mucking with Motif's resource framework.
>   The former has far lower odds of leading directly to terminal
>   insanity.                                            -- Dan Martinez





More information about the Python-list mailing list