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

Ron Adam rrr at ronadam.com
Sun Oct 5 15:21:50 CEST 2008



Greg Ewing wrote:

> It's true that with a 'let' statement or equivalent,
> there's no strict need for a change to the for-loop,
> since you can always say
> 
>   for i in range(10):
>     let i = i:
>       funcs.append(lambda: i)
> 
> But it's an annoying and odd-looking piece of
> boilerplate to have to use, and in that respect is
> similar to the existing solutions of inserting another
> lambda or using a default argument value.


Seems to me this is very similar to decorators.

 >>> L = []
 >>> def get_f(i):
...     return lambda:i
...
 >>> for i in range(10):
...     L.append(get_f(i))
...
 >>> L
[<function <lambda> at 0x7f6598375320>, <function <lambda> at 
0x7f6598375398>, <function <lambda> at 0x7f6598375410>, <function <lambda> 
at 0x7f6598375488>, <function <lambda> at 0x7f6598375500>, <function 
<lambda> at 0x7f6598375578>, <function <lambda> at 0x7f65983755f0>, 
<function <lambda> at 0x7f6598375668>, <function <lambda> at 
0x7f65983756e0>, <function <lambda> at 0x7f6598375758>]
 >>> for f in L:
...     f()
...
0
1
2
3
4
5
6
7
8
9


Ron




More information about the Python-ideas mailing list