[Python-ideas] Changing semantics of for-loop variable

Jim Jewett jimjjewett at gmail.com
Fri Sep 30 16:17:22 CEST 2011


On Fri, Sep 30, 2011 at 1:06 AM, Terry Reedy <tjreedy at udel.edu> wrote:
> On 9/29/2011 5:31 PM, Greg Ewing wrote:

>> If the loop variable is referenced from an inner scope,
>> instead of replacing the contents of its cell, create
>> a *new* cell on each iteration.

> Since loop variables do not normally have cells, I really do not understand
> from this what you are proposing.  What I do understand is that you would
> have the content of the body of a loop change the behavior of the loop.

Not really.  If the loop (or other) variable is not used in creating
closures, then it doesn't really matter whether the variable is stored
as a local or a cell -- it happens to be stored as a local for speed
reasons.

If a variable (including the loop variable) is used inside a closure,
then it already creates a cell.  This means that loop content already
affects the way the loop is compiled, though again, it affects only
efficiency, not semantics.

The difference is that now the loop will create N separate cells
instead of just one, so that each closure will see its own private
variable, instead of all sharing the same one.  That is a semantic
difference, but if the closed-over variable is also a loop variable,
it will normally be a bugfix.

> I have used about 20 languages and in all of them, a 'variable' refers to a
> specific memory block or or name.

There are languages (Erlang is the best known) that make "variables"
write-once; in those cases, loops will always create N separate
"variables".  (Expensive on memory; good for concurrency.)  This
proposal says that python should do so when (and perhaps only when)
those separate variable instances are used in different closures.

-jJ



More information about the Python-ideas mailing list