unintuitive for-loop behavior

Gregory Ewing greg.ewing at canterbury.ac.nz
Fri Sep 30 00:53:13 EDT 2016


namenobodywants at gmail.com wrote:
 > can anyone help to reconcile me to this semantics?

Not really. Most people agree that it's not desirable
behaviour, but we've ended up here due to a convoluted
history, and there doesn't seem to be a good way to
fix it without breaking a lot of existing code.

Chris Angelico wrote:
> You could, in theory, have the name be unbound after the loop, but it's
> usually not beneficial to do so, and can be detrimental.

It also wouldn't help at all with this problem.

There *is* something that could be done, at least in
CPython: if the loop variable is referenced by a nested
function, then create a new cell for it each time
round the loop, instead of updating the contents of
the existing cell.

This would be backwards-compatible in almost all cases.
The last value would still be accessible after the
loop finishes, and other assignments to the loop
variable in the same function would work the same
way as always.

Guido doesn't like this idea, though, because it
depends on CPython implementation details, and other
Python implementations could have trouble matching
these semantics.

-- 
Greg



More information about the Python-list mailing list