473,320 Members | 2,112 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

problem using lambdas for deferred callbacks

edd
I tried searching for an answer to this in the google groups archives
but I failed to come up with anything. So I hope no one minds me asking
this, though I'm sure it's been asked a million times before.

I was hoping that the following code would print "Hello, world!", one
character per line. But instead it prints an exclamation mark for each
character of the string. I'm sure it's no coincidence that the last
value of c is '!', but beyond that I don't understand what's happening.

# --- begin code ---
def callback(arg):
print arg

funcs = []
for c in 'Hello, world!':
funcs.append(lambda: callback(c))

for f in funcs:
f()
# --- end code ---

What I'm trying to do is create a 0-args callback by binding an
argument to a 1-arg function. But failing, miserably :)

I'm using Python 2.3.5 as installed by default on Mac OS X 10.4 if it
matters.

Thanks,

Edd

Dec 10 '06 #1
3 1043
In <11**********************@79g2000cws.googlegroups. com>, edd wrote:
I was hoping that the following code would print "Hello, world!", one
character per line. But instead it prints an exclamation mark for each
character of the string. I'm sure it's no coincidence that the last
value of c is '!', but beyond that I don't understand what's happening.
If you call the lambda function the name `c` is looked up in the
"environment". It's not local to the function.
# --- begin code ---
def callback(arg):
print arg

funcs = []
for c in 'Hello, world!':
funcs.append(lambda: callback(c))
Change this line to:

funcs.append(lambda x=c: callback(x))

Now the `c` is bound to the default argument `x` at definition time.

Ciao,
Marc 'BlackJack' Rintsch
Dec 10 '06 #2
ed*@nunswithguns.net wrote:
I was hoping that the following code would print "Hello, world!", one
character per line. But instead it prints an exclamation mark for each
character of the string. I'm sure it's no coincidence that the last
value of c is '!', but beyond that I don't understand what's happening.

# --- begin code ---
def callback(arg):
print arg

funcs = []
for c in 'Hello, world!':
funcs.append(lambda: callback(c))
the "lambda" introduces a new function scope, and since the "c" variable
isn't defined in there, it's bound to the variable with the same name
from the outer scope. the problem here is that it's bound to the
*variable*, not the object, so *all* callbacks will use the same value.

there are several ways to bind to an object value instead; the easiest
in this case is to use a default argument value:

for c in 'Hello, world!':
funcs.append(lambda c=c: callback(c))

this turns the inner "c" variable to an argument that defaults to the
value of the outer "c" at the time the lambda was created.

</F>

Dec 10 '06 #3
edd
Many thanks to you both!

Edd

Dec 10 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: gong | last post by:
hi i would like to pickle a lambda; according to the library docs in 2.3, i believe this shouldnt be possible, since a lambda is not a function defined at the top level of a module (?) ...
6
by: andrea.gavana | last post by:
Hello NG, probably this is a basic question, but I'm going crazy... I am unable to find an answer. Suppose that I have a file (that I called "Errors.txt") which contains these lines: MULTIPLY...
0
by: ck388 | last post by:
For some reason when I enable the callback feature of the gridview I still get a page refresh, that is it seems like there is a postback that occurs, not a callback which is just supposed to update...
8
by: Frank van Vugt | last post by:
Hi, If during a transaction a number of deferred triggers are fired, what will be their execution order upon the commit? Will they be executed in order of firing or alfabetically or...
4
by: rzimerman | last post by:
I'm hoping to write a program that will read any number of urls from stdin (1 per line), download them, and process them. So far my script (below) works well for small numbers of urls. However, it...
10
by: amitabh.mehra | last post by:
Hi I havent used MQT before. Read the online tips and tutorials but none seems to give any hint for my problem. I have a base table (base_table) as: st varchar(25) default...
10
by: George Sakkis | last post by:
I'd like some feedback on a solution to a variant of the producer- consumer problem. My first few attempts turned out to deadlock occasionally; this one seems to be deadlock-free so far but I can't...
1
by: Jean-Paul Calderone | last post by:
On Tue, 10 Jun 2008 22:46:37 -0700 (PDT), George Sakkis <george.sakkis@gmail.comwrote: This isn't true. Access is synchronized automatically by virtue of the fact that there is no pre-emptive...
16
by: rowe_newsgroups | last post by:
Ok, I'm tired and I'm sure I know the answer to this, but I can't seem to come up with it right now. What is the VB.NET equivalent to the following C# code? /////////////...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.