On Wed, 3 May 2006, Igor wrote:

> And I thought I understood python pretty well. Until I got hit by this:
>
>>>> def f(x):
> ...   print x
>
>>>> cb = [lambda :f(what) for what in "1234"]
>>>> for c in cb:c()
> 4
> 4
> 4
> 4

Hi Igor,

I think you're getting caught by something that isn't quite related to 
closures really, but with the way Python does for loops (or assignment, 
for that matter.)


Take a look at the following example:

######
>>> import sys
>>> def sequence_function(seq):
...     x = [None]
...     results = []
...     for s in seq:
...         x[0] = s
...         results.append(lambda: sys.stdout.write("hello %s" % x[0]))
...     return results
...
######

Try it out; does it behave in an expected way to you?  If so, compare it 
against what you had earlier.


The core of the problem is that Python's for loop mutates 's', so that all 
the newly defined functions refer to the same s.


Best of wishes!
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to