[Python-Dev] PEP for Better Control of Nested Lexical Scopes

Thomas Wouters thomas at xs4all.net
Thu Feb 23 22:24:02 CET 2006


On Thu, Feb 23, 2006 at 05:25:30PM +1300, Greg Ewing wrote:
> Samuele Pedroni wrote:
> 
> > If you are looking for rough edges about nested scopes in Python
> > this is probably worse:
> > 
> >  >>> x = []
> >  >>> for i in range(10):
> > ...   x.append(lambda : i)
> > ...
> >  >>> [y() for y in x]
> > [9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
> 
> As an aside, is there any chance that this could be
> changed in 3.0? I.e. have the for-loop create a new
> binding for the loop variable on each iteration.

You can't do that without introducing a whole new scope for the body of the
'for' loop, and that means (in the current rules) you can't assign to any
function-local names in the for loop. The nested scope in that 'lambda'
refers to the 'slot' for the variable 'i' in the outer namespace (in this
case, the global one.) You can't 'remove' the binding, either; 'del' will
not allow you to.

-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!


More information about the Python-Dev mailing list