[Python-ideas] For-loop variable scope: simultaneous possession and ingestion of cake

Aahz aahz at pythoncraft.com
Fri Oct 3 16:31:45 CEST 2008


On Fri, Oct 03, 2008, Greg Ewing wrote:
>
> Previous proposals to make for-loop variables local to the loop have
> stumbled on the problem of existing code that relies on the loop
> variable keeping its value after exiting the loop, and it seems that
> this is regarded as a desirable feature.

Very yes, I use this constantly.

> So I'd like to propose something that would satisfy
> both requirements:
>
> 0. There is no change if the loop variable is not
>    referenced by a nested function defined in the loop
>    body. The vast majority of loop code will therefore
>    be completely unaffected.
>
> 1. If the loop variable is referenced by such a nested
>    function, a new local scope is effectively created
>    to hold each successive value of the loop variable.
>
> 2. Upon exiting the loop, the final value of the loop
>    variable is copied into the surrounding scope, for
>    use by code outside the loop body.
>
> Rules 0 and 1 would also apply to list comprehensions
> and generator expressions.
>
> There is a very simple and efficient way to implement
> this in current CPython: If the loop variable is referenced
> by a nested function, it will be in a cell. Instead of
> rebinding the existing cell, each time around the loop
> a new cell is created, replacing the previous cell.
> Immediately before exiting the loop, one more new cell
> is created and the final value of the loop variable
> copied into it.
>
> Implementations other than CPython that aren't using
> cells may need to do something more traditional, such
> as compiling the loop body as a separate function.

You'll need to make sure that exceptions don't break this.  I'm not sure
to what extent the current test suite covers the current behavior, I
think that beefing it up is a necessary precondition to trying this
approach.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"...if I were on life-support, I'd rather have it run by a Gameboy than a
Windows box."  --Cliff Wells, comp.lang.python, 3/13/2002



More information about the Python-ideas mailing list