tags:

views:

68

answers:

1

Hi,

Could some explain how call back methods work, and if possible, give me an example in Python? So as far as I understand them, they are methods which are provided by the user of an API, to the API, so that the user doesn't have to wait till that particular API function completes. So does the user program continue executing, and once the callback method is called by the API, return to point in the program where the callback method was provided? How does a callback method essentially affect the 'flow' of a program?

Sorry if I'm being vague here.

+6  A: 

Callbacks are just user-supplied hooks. They allow you to specify what function to call in case of certain events. re.sub has a callback, but it sounds like you are dealing with a GUI, so I'll give a GUI example:

Here is a very simple example of a callback:

from Tkinter import *

master = Tk()

def my_callback():
    print('Running my_callback')

b = Button(master, text="OK", command=my_callback)
b.pack()

mainloop()

When you press the OK button, the program prints "Running my_callback".

If you play around with this code:

from Tkinter import *
import time

master = Tk()

def my_callback():
    print('Starting my_callback')
    time.sleep(5)
    print('Ending my_callback')    

def my_callback2():
    print('Starting my_callback2')
    time.sleep(5)
    print('Ending my_callback2')    

b = Button(master, text="OK", command=my_callback)
b.pack()
b = Button(master, text="OK2", command=my_callback2)
b.pack()

mainloop()

you'll see that pressing either button blocks the GUI from responding until the callback finishes. So the "user does have to wait till that particular API function completes".

unutbu
Thanks for your reply. So the only difference between a callback (API) method and a regular (API) method is that instead of simply returning a value, the callback method in turn calls a user method when complete?
iman453
Above, the "regular method" (erm, better called API object) is `Button`. The "callback method" (better called callback function) is `my_callback`. The difference between `Button` and `my_callback` is that the API supplies the definition of `Button` and the user of the API need only define `my_callback`. Deep inside the API's code is some logic which says if the user presses the button, call some function. To customize the button, the API allows the API user to hook up `my_command` as the function to call. That's what callbacks do. They hook into other code that you generally don't control.
unutbu
Got it, Thanks!
iman453