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

Ronald Oussoren ronaldoussoren at mac.com
Tue Oct 4 14:22:45 CEST 2011


On 30 Sep, 2011, at 16:17, Jim Jewett wrote:

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

What worries me with this proposal is that it only affects the loop variable, and not other variables. This makes it easy to introduce subtle bugs when you forget this. I often have code like this when using closures in a loop:

    for val in sequence:
        other = lookup(val)
        result.append(lambda val=val, other=other): doit(val, other))

Greg's proposal means that 'val=val' would no longer be needed, but you'd still need to use the default argument trick for other variables. The difference between the behavior for the loop variable and other variables is also relatively hard to explain. 

Ronald
-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/pkcs7-signature
Size: 2224 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20111004/bce20e54/attachment.bin>


More information about the Python-ideas mailing list