[Python-Dev] 2.5 and beyond

Terry Reedy tjreedy at udel.edu
Sat Jul 1 07:00:40 CEST 2006


"Giovanni Bajo" <rasky at develer.com> wrote in message 
news:027f01c69caf$b1c20450$d1b12997 at bagio...
> [Giovanni Bajo]
>> Yes but:
>>
>>>>> a = []
>>>>> for i in range(10):
>> ...     a.append(lambda: i)
>> ...
>>>>> print [x() for x in a]
>> [9, 9, 9, 9, 9, 9, 9, 9, 9, 9]

>. Do you  agree that it would be ideal if the above code
> generated range(10) instead of  [9]*10,

No.  You are trying to reify an optical illusion resulting from putting a 
constant function definition inside a loop.  Making the meaning of  'def 
f(): return i' depend on the definition-time context by partially and 
variably evaluating the body would make code much harder to read and 
understand.  Consider:

if a: i=666
<intervening code>
def f(): return i

> At
> worse, couldn't Python do the "i=i" trick by itself when it sees that `i` 
> is a
> local in the outer scope? Right now I can't think off-hand of a case in 
> which
> this would break things.

It would make code more fragile.

for i in range(666): print name[i]
...
<intervening code>
...
def total(num): return cost[item]*num

Now someone decides first loop should have more expressive loop var name 
and changes the first line to

for item in range(666): print name[item]

and the meaning of total is completely changed.  Adding such long-range 
coupling between language statements strikes me as a poor idea.

Terry Jan Reedy





More information about the Python-Dev mailing list