Main Content

What is a callback?

Archive - Originally posted on "The Horse's Mouth" - 2005-07-22 09:29:52 - Graham Ellis

When you write a program, you're usually providing the filling for a sandwich.

At the top level, you have the operating system and the compiler or interpreter for the particular language you're using and this provides you with the mechanism to start and end your program, and for it to share the resources of your computer with other processes. At the bottom level, you call libraries (functions, subs, methods, procs ...) that are provided with the language to perform all those common tasks that are required in many programs - ranging from outputting results to a file and converting dates through validating that a user's input matches a particular regular expression to testing if one number is greater than another. It's your job as programmer to provide the bit between.

Regular code

Example (in Python). Here's a piece of code that takes the number of staff at four companies and works out how many cricket teams there are (potentially) in each company.


def teams(wot):
return wot/11

def mymap(action,source):
retlist = []
for val in source:
retlist.append(action(val))
return retlist

co_sizes = [27,3,46,129]

cricket = mymap(teams,co_sizes)
print "Number of cricket teams ...",cricket


Python functions / methods called at the bottom level include __div__, __str__, append and print and the results of running the program are:

Number of cricket teams ... [2, 0, 4, 11]

Using a callback

A callback is where a bottom level function (i.e. one that's provided with the language) calls code that you as the programmer provided. In the example above, the main program calls the mymap function, which in turn calls the team function, and both the mymap and the team function were part of the user code. But why? Surely, the running of the same (user) function of every member of a list is a common requirement and the programming language itself should provide the capabilty. And, yes, in Python it does - it's the built in map function ...


def teams(wot):
return wot/11

co_sizes = [27,3,46,129]

soccer = map(teams,co_sizes)

print "Number of soccer teams ...",soccer


Exactly the same calculation as the earlier example but here ...
user code calls the python function map
python function map CALLS BACK to the user code (the function called teams)

Note the code is much shorter and - once you're aware what's going on - much easier.

Common applications of callbacks
1. Mapping functions such as the example above
2. Sort routines, where the langauge provides the sort management and calls back to user provided functions to work out whether one record comes before or after another
3. GUIs (Graphic user interfaces) where actions are defined in functions / procs that the main event handler calls back to.