annonymous functions -- how to

Dave Benjamin dave.benjamin at gmail.com
Thu May 5 12:28:11 EDT 2005


Peter Hansen wrote:
> I doubt there's a valid usecase for a "anonymous" function that has more 
> than a line or two.  Personally, I don't think there's a good usecase 
> for an anonymous function longer than one line...

The case that I keep running into regards event-driven programming. I 
need to do a series of operations that are tied together asynchronously 
via callback functions, but I still want the actions to read in-order. 
With anonymous functions (and I mean the ones that you can use within 
expressions, Bengt ;) ), I could write something like the following:

def add_thingy():
     with_next_thingy_id(def(thingy_id):
         print 'got thingy id:', thingy_id
         with_next_doodad_id(def(doodad_id):
             pring 'got doodad id:', doodad_id
             with_new_thingy_doodad(thingy_id, doodad_id,
                                    def(thingy_doodad):
                 print 'thingy doodad created, froobling...'
                 frooble(thingy_doodad)
                 print 'froobling complete'
             )
         )
     )

In this case, having to name these callback functions is tiring and 
awkward, and (IMHO) disrupts the flow of my function:

def add_thingy():
     def next_thingy_id_func(thingy_id):
         print 'got thingy id:', thingy_id
         def next_doodad_id_func(doodad_id):
             print 'got doodad id:', doodad_id
             def new_thingy_doodad_func(thingy_doodad):
                 print 'thingy doodad created, froobling...'
                 frooble(thingy_doodad)
                 print 'froobling complete'
             with_new_thingy_doodad(thingy_id, doodad_id,
                                    new_thingy_doodad_func)
         with_next_doodad_id(next_doodad_id_func)
     with_next_thingy_id(next_thingy_id_func)

There is no reason why these callbacks would necessarily be one-liners 
or ten-liners. I suppose this problem could be solved by defining all 
the functions at the top-level (or by using bound methods of an object), 
but to me this is harder to maintain and doesn't read as well.

Not life or death, but there's at least one use case that I would at 
least consider "valid". Your definition of "valid" may differ, of course. =)

Dave



More information about the Python-list mailing list