Securing a future for anonymous functions in Python

David Bolen db3l at fitlinxx.com
Fri Dec 31 20:15:59 CET 2004


Scott David Daniels <Scott.Daniels at Acm.Org> writes:

> David Bolen wrote:
> > 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.
> 
> But this sequence contains an error of the same form as the "fat":

"this" being which of the two scenarios you quote above?

>      while test() != False:
>           ...code...

I'm not sure I follow the "error" in this snippet...

> The right sequence using lambda is:
>       d = some_deferred_function()
>       d.addCallback(next_function)
>       d.addCallback(lambda blah: third_function(otherargs, blah))
>       d.addCallback(last_function)

By what metric are you judging "right"?

In my scenario, the functions next_function and last_function are not
written to expect any arguments, so they can't be passed straight into
addCallback because any deferred callback will automatically receive
the result of the prior deferred callback in the chain (this is how
Twisted handles asynchronous callbacks for pending operations).
Someone has to absorb that argument (either the lambda, or
next_function itself, which if it is an existing function, needs to be
handled by a wrapper, ala my second example).

Your "right" sequence simply isn't equivalent to what I wrote.
Whether or not next_function is fixable to be used this way is a
separate point, but then you're discussing two different scenarios,
and not two ways to write one scenario.

-- David



More information about the Python-list mailing list