[Python-Dev] Generator details

Guido van Rossum guido@CNRI.Reston.VA.US
Sun, 11 Jul 1999 23:01:04 -0400


[Tim seems to be explaining why len(l)+1 and not len(l) -- but I was
really thinking about len(l)+1 vs. 1.]

> OTOH, the notion that the "finally" clause should get triggered at all the
> first len(l) times is debatable.  If I picture it as a "resumable function"
> then, sure, it should; but if I picture the caller as bouncing control back
> & forth with the generator, coroutine style, then suspension is a just a
> pause in the generator's execution.  The latter is probably the more natural
> way to picture it, eh?

*This* is what I was getting at, and it points in favor of a SUSPEND
opcode since I don't know how to do that in the multiple-return.  As
you point out, there can be various things on the various in-frame
stacks (value stack and block stack) that all get discarded by a
return, and that no restart_frame() can restore (unless get_frame()
returns a *copy* of the frame, which seems to be defeating the
purpose).

> OTOH, the possibility that someone *can* do an explicit get_frame suggests
> that "for" shouldn't assume it's the master of the universe <wink>.  Perhaps
> the user's intent was to generate the first 100 values in a for loop, then
> break out, analyze the results, and decide whether to resume it again by
> hand (I've done stuff like that ...).  So there's also a case to be made for
> saying that a "finally" clause wrapping a generator body will only be
> executed if the generator body raises an exception or the generator itself
> decides it's done; i.e. iff it triggers while the generator is actively
> running.

Hmm...  I think that if the generator is started by a for loop, it's
okay for the loop to assume it is the master of the universe -- just
like there's no force in the world (apart from illegal C code :) that
can change the hidden loop counter in present-day for loop.

--Guido van Rossum (home page: http://www.python.org/~guido/)