[Python-ideas] For-loop variable scope: simultaneous possession and ingestion of cake

Oleg Broytmann phd at phd.pp.ru
Fri Oct 3 12:54:17 CEST 2008

On Fri, Oct 03, 2008 at 10:37:39PM +1200, Greg Ewing wrote:
>   lst = []
>   for i in range(10):
>     lst.append(lambda: i)
>   for f in lst:
>     print f()
> printing 9 ten times instead of 0 to 9.

   I lost count how many times I've stumbled upon that wart.

> There is a very simple and efficient way to implement
> this in current CPython: If the loop variable is referenced
> by a nested function, it will be in a cell. Instead of
> rebinding the existing cell, each time around the loop
> a new cell is created, replacing the previous cell.
> Immediately before exiting the loop, one more new cell
> is created and the final value of the loop variable
> copied into it.
> The benefit would be that almost all code involving
> loops and nested functions would behave intuitively,


     Oleg Broytmann            http://phd.pp.ru/            phd at phd.pp.ru
           Programmers don't die, they just GOSUB without RETURN.

More information about the Python-ideas mailing list