[Python-ideas] Explicit variable capture list

Chris Angelico rosuav at gmail.com
Sat Jan 23 00:06:36 EST 2016


On Sat, Jan 23, 2016 at 3:50 PM, Andrew Barnert via Python-ideas
<python-ideas at python.org> wrote:
> Finally, Terry suggested a completely different solution to the problem:
> don't change closures; change for loops. Make them create a new variable
> each time through the loop, instead of reusing the same variable. When the
> variable isn't captured, this would make no difference, but when it is,
> closures from different iterations would capture different variables (and
> therefore different cells). For backward-compatibility reasons, this might
> have to be optional, which means new syntax; he proposed "for new i in
> range(10):".

Not just for backward compatibility. Python's scoping and assignment
rules are currently very straight-forward: assignment creates a local
name unless told otherwise by a global/nonlocal declaration, and *all*
name binding follows the same rules as assignment. Off the top of my
head, I can think of two special cases, neither of which is truly a
change to the binding semantics: "except X as Y:" triggers an
unbinding at the end of the block, and comprehensions have a hidden
function boundary that means their iteration variables are more local
than you might think. Making for loops behave differently by default
would be a stark break from that tidiness.

It seems odd to change this on the loop, though. Is there any reason
to use "for new i in range(10):" if you're not making a series of
nested functions? Seems most logical to make this a special way of
creating functions, not of looping.

ChrisA


More information about the Python-ideas mailing list