[Tutor] Learning about callbaks

Dave Kuhlman dkuhlman at rexx.com
Sat Dec 29 19:58:26 CET 2007


On Sat, Dec 29, 2007 at 04:58:39PM +0100, Michael Bernhard Arp S?rensen wrote:
> Hi there.
> 
> I want to learn about callbacks because we use it at work in our software.
> 
> I there a short "hello world"-like version of a callback example?
> 

In Python, any object that can be *called* can be considered a
call-back.  The Pythonic way of describing these objects is to say
that they are "callable".  You can detect whether an object is
callable by using "dir(obj)", then looking for an attribute named
"__call__".

Objects defined with "def" (functions and methods) and "lambda"
provide that automatically.  And, if you implement a class
containing a method name "__call__", then instances of that class
will be callable (and can be used as call-backs) also.

Python's consistent use of first-class objects makes using
callables/call-backs so simple that it is almost hard to
explain.  Just stuff that callable (function, method, lambda, or
instance with a "__call__" method) into a data structure or pass it
to a function, then when you are ready to use it, apply the
function call "operator" (parentheses).

Here is a trivial example:

    def f1(x):
        print 'f1: %s' % x

    def f2(x):
        print 'f2: %s' % x

    def use_them(funcs):
        for func in funcs:
            func('abcd')

    def test():
        funcs = [f1, f2]
        use_them(funcs)

    test()

- Dave



-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman


More information about the Tutor mailing list