Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > problem with lambda / closures

Reply
Thread Tools

problem with lambda / closures

 
 
Louis Steinberg
Guest
Posts: n/a
 
      11-30-2009
I have run into what seems to be a major bug, but given my short
exposure to Python is probably just a feature:

running
Python 2.6.4 (r264:75821M, Oct 27 2009, 19:48:32)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin

with file foo.py containing:

============================== clip here ============
def p(d):
print d


l=[ ]
for k in [1,2,3]:
l.append(lambda : p(k))

for f in l:
f()

============================== clip here ============
I get output
3
3
3
instead of
1
2
3
which I would expect. Can anyone explain this or give me a
workaround? Thank you



 
Reply With Quote
 
 
 
 
Marco Mariani
Guest
Posts: n/a
 
      11-30-2009
Louis Steinberg wrote:

> I have run into what seems to be a major bug, but given my short
> exposure to Python is probably just a feature:



Yes, it works as advertised :-/


> which I would expect. Can anyone explain this or give me a workaround?


like this?


> def p(d):
> print d
>
>
> l=[ ]
> for k in [1,2,3]:
> l.append(lambda k=k: p(k))
>
> for f in l:
> f()

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
anonymous closures with Proc,new, lambda and -> Stu Ruby 31 04-27-2011 10:06 PM
Re: problem with lambda / closures Terry Reedy Python 2 12-01-2009 09:50 PM
Closures / lambda question Aldric Giacomoni Ruby 12 10-30-2009 02:41 PM
Re: Lambda as declarative idiom (was RE: what is lambda used for inreal code?) Roman Suzi Python 13 01-07-2005 09:33 PM



Advertisments
 



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57