Securing a future for anonymous functions in Python

David Bolen db3l at fitlinxx.com
Thu Dec 30 16:44:39 EST 2004


Ian Bicking <ianb at colorstudy.com> writes:

> The one motivation I can see for function expressions is
> callback-oriented programming, like:
> 
>    get_web_page(url,
>      when_retrieved={page |
>        give_page_to_other_object(munge_page(page))})

This is my primary use case for lambda's nowadays as well - typically
just to provide a way to convert the input to a callback into a call
to some other routine.  I do a lot of Twisted stuff, whose deferred
objects make heavy use of single parameter callbacks, and often you
just want to call the next method in sequence, with some minor change
(or to ignore) the last result.

So for example, an asynchronous sequence of operations might be like:

    d = some_deferred_function()
    d.addCallback(lambda x: next_function())
    d.addCallback(lambda blah: third_function(otherargs, blah))
    d.addCallback(lambda x: last_function())

which to me is more readable (in terms of seeing the sequence of
operations being performed in their proper order), then something like:

    def cb_next(x):
        return next_function()
    def cb_third(blah, otherargs):
        return third_function(otherargs, blah)
    def cb_last(x):
        return last_function()

    d = some_deferred_function()
    d.addCallback(cb_next)
    d.addCallback(cb_third, otherargs)
    d.addCallback(cb_next)
        
which has an extra layer of naming (the callback functions), and
requires more effort to follow the flow of what is really just a simple
sequence of three functions being called.

> I think this specific use case -- defining callbacks -- should be
> addressed, rather than proposing a solution to something that isn't
> necessary.  (...)

I'd be interested in this approach too, especially if it made it simpler
to handle simple manipulation of callback arguments (e.g., since I often
ignore a successful prior result in a callback in order to just move on
to the next function in sequence).

-- David



More information about the Python-list mailing list