RELEASED Python 2.4, alpha 1

Michele Simionato michele.simionato at gmail.com
Sat Jul 10 05:50:20 CEST 2004


Christopher T King <squirrel at WPI.EDU> wrote in message news:<Pine.LNX.4.44.0407091448120.9852-100000 at ccc3.wpi.edu>...
> 
> I think this is a property of lambdas (or functions in general), rather 
> than comprehensions:
> 
> >>> i=1
> >>> f1=lambda: i
> >>> i=2
> >>> f2=lambda: i
> >>> i=3
> >>> f3=lambda: i
> >>> f1()
>  3
> >>> f2()
>  3
> >>> f3()
> 3

No, it is due to the fact that looping does not create a new lexical
scope. This was discussed in depth in the past. Google in this
newgroup.
Scheme does it right:

; scheme is the same as in Python here
msi> (define i 1)
msi> (define (f1) i)
msi> (set! i 2)
msi> (define (f2) i)
msi> (set! i 3)
msi> (define (f3) i)
msi> (f1)
3
msi> (f2)
3
msi> (f3)
3
; Scheme is different in looping constructs
msi> (define-values (f1 f2 f3) (apply values (map (lambda(i) (lambda()
i)) '(1 2 3))))
msi> (f1)
1
msi> (f2)
2
msi> (f3)
3

After long discussions in previous threads, I do understand well why
it is so;
I also understand why in regular "for" loops Python behavior has to be
the one
it is, since "for" does not create a new lexical scope. In my opinion,
however, it would have made more sense to have generator-expressions
with
early bindings. 
But, anyway, Tim Peters is right that this issue does not make a
big difference for casual programmers and sophysticated programmers 
know the workarounds.

            Michele Simionato



More information about the Python-list mailing list