[Tutor] Script Feedback

Steven D'Aprano steve at pearwood.info
Thu Apr 1 00:40:14 CEST 2010

On Wed, 31 Mar 2010 10:54:34 am Damon Timm wrote:

> > Separate the underlying functionality from the application-level
> > code. These functions should NEVER print anything: they do all
> > communication through call-backs, or by returning a value, or
> > raising an exception.
> I tried to implement this, however, I am not sure how the 'callback'
> works ... is that just a function that a user would pass to *my*
> function that gets called at the end of the script?

Not necessarily at the end of the script.

You usually find callbacks used a lot in coding for graphical user 
interfaces (GUIs). For instance, the GUI framework might provide a 
Button class. The caller creates a new Button object, and provides a 
callback function which gets called automatically by the framework 
whenever the user clicks the button.

The built-in function map is very similar. map is more or less 
equivalent to the following:

def map(callback, sequence):
    result = []
    for item in sequence:
    return result

except the real map is more efficient, and accepts multiple sequences. 
It's not common to describe the function argument to map as a callback, 
but that's essentially what it is. In this example, the callback 
function needs to be a function that takes a single arbitrary argument. 
The caller can pass any function they like, so long as it takes a 
single argument, and map promises to call that function with every item 
in the sequence.

There's nothing special about callbacks, except that they have to take 
the arguments which the library function promises to supply.

Steven D'Aprano

More information about the Tutor mailing list