Securing a future for anonymous functions in Python

Ian Bicking ianb at colorstudy.com
Fri Dec 31 18:54:51 CET 2004


David Bolen wrote:
> 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())

Steven proposed an ignoreargs function, and the partial function offers 
the other side (http://www.python.org/peps/pep-0309.html).  So this 
would become:

d = some_deferred_function()
d.addCallback(ignoreargs(next_function, 1))
d.addCallback(partial(third_function, otherargs))
d.addCallback(ignoreargs(last_function, 1))

I'm not sure this is "better" than it is with lambda.  It's actually 
considerably less readable to me.  Hmm... well, that makes me less 
excited about those...

-- 
Ian Bicking  /  ianb at colorstudy.com  / http://blog.ianbicking.org



More information about the Python-list mailing list