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

Dillon Collins dillonco at comcast.net
Sat Oct 4 02:16:02 CEST 2008


On Friday 03 October 2008, Terry Reedy wrote:
> def f(i): return lambda: i
> for i in range(10):
>      lst.append(f(i))

Or better yet:
for i in range(10):
     lst.append((lambda i: lambda:i)(i))

But I'm probably not helping ;).

I'd have to say, though, that if this was a problem, it'd have to be with 
lambda.  Most people don't expect control blocks to have their own context, 
they only expect functions to have them, and then a 'global' one.  Nested 
functions are awkward because they have their own context but can fall back 
to the parent if need be and people don't really see the sort of local-global 
aspect of closures.

Also, how awful would the 'nonlocal' boilerplate be:

count = 0
for i in lst:
    nonlocal count 
    if i is not None:
        count += i

And, unless I'm mistaken, this would make for loops incompatible with 
comprehensions:

>>> a = [(lambda : i) for i in range(10)]
>>> b = []
>>> for i in range(10):
>>>     b.append(lambda : i)
>>> del i
>>> print [j() for j in a]
NameError: global name 'i' is not defined
>>> print [j() for j in b]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

That's not good.



More information about the Python-ideas mailing list