[Tutor] Learning about callbaks

Alan Gauld alan.gauld at btinternet.com
Sat Dec 29 18:39:56 CET 2007


"Michael Bernhard Arp Sørensen" <michaelarpsorensen at stevnstrup.dk> 
wrote

> I want to learn about callbacks because we use it at work in our 
> software.

Can you be more specific about what you want to know. Callbacks are
used in many different ways from event handling methods in a GUI
to network programming to simulating synchronous protocols over
an asynchronous connection.

> I there a short "hello world"-like version of a callback example?

See almost any GUI tutorial.
The recent thread "Closing GUI program" had the following example
from Michael Goldwasser

#-------------------------------------------
from Tkinter import Tk,Label

def onClose():
    root.destroy()   # stops the main loop and interpreter

root = Tk()
root.protocol("WM_DELETE_WINDOW", onClose)  # handle event when window 
is closed by user
z = Label(root, text="Hello World!")
z.grid()
root.mainloop()
#-------------------------------------------


In this example the onClose() event handler is a callback function.

The folowing pseusdo code shows how the principle can be used for
asynchronous network programming:

waiting = {}     # list of objects awaiting responses
id = 0

def sendToServer(msg, callback)
       msgSent = prepareMessage(msg)
       id = server.send(msgSent)
       waiting[id] = (msg, callback)

def func1()
     msg = prepareData()
     sendToServer(msg, func1_cont)

def func1_cont(original, result)
     x,y,z = result.getValues()
     processData(x,y,z,original.p,original.q)

while server.listen()
      msg = server.recv()
      id = msg.getID()
      oldMessage = waiting[id][0]
      callback =  waiting[id][1]
      callback(oldmessage, msg)
      del(waiting[id])

In this example we can think of the main application calling func.
func1 needs to send a message to a server and process the response
but the server has an asynchronous protocol so we split the function
into func1 and func1_cont at the point of calling the server. Then
when the server send us the response we pull the stored state out
of the dictionary and combine it with the server data to complete
the func1 processing via the func1_cont callback.

In practice we'd probably store the date/time with the transaction
data so that we can check for timeouts etc in a separate thread...

The important thing with all callbacks is that you match up the
data expected by the callback with the data actually available
at the point of calling it. In this case we take the architectural
decision to pass callback functions the old and new data structures.
We could alternatively have passed the transaction id and let the
callback retrieve (and delete) the data from the waiting list.

I hope that all makes sense.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list