[Python-ideas] For loop binding (was Re: Tweaking closures ...)
greg.ewing at canterbury.ac.nz
Thu Sep 29 12:52:43 CEST 2011
Terry Reedy wrote:
> No, for loops *do* rebind loop variables each time around.
I probably should have avoided the word "bind", because it
can be ambiguous. What I mean is that it assigns a different
value to the same variable instead of creating a new
variable. This is different from what equivalent constructs
in some other languages do.
> People are
> assuming that 'i' is immediately bound to its 'current' value,
Yes, that's another possible misinterpretation they may be
making -- if they're thinking that deeply about the issue
However, changing the language to make *that* true would
break a lot of other things, such as mutual recursion, and
isn't really an option.
> The posted 'surprise code' typically uses list
> comps. So changing for loops to be like list comps would have no effect
> on that mis-assumptions and the resulting surprise.
Agreed, because list comps in Python have the same problem --
even if the name is local to the list comp, it's still just
one variable being reassigned.
I only mentioned list comps as a precedent for making some
kind of change to the way a loop variable is treated. I
didn't mean to suggest that the way they currently work
would solve the closure problem.
More information about the Python-ideas