Turning a callback function into a generator

cmdrrickhunter@yaho.com conrad.ammon at gmail.com
Mon Jul 3 05:52:54 EDT 2006


Peter Otten wrote:
> Kirk McDonald wrote:
>
> > Let's say I have a function that takes a callback function as a
> > parameter, and uses it to describe an iteration:
> >
> > def func(callback):
> >      for i in [1, 2, 3, 4, 5]:
> >          callback(i)
> >

Which object is immutable? the callback or the function?  If its the
callback then

def func(callback):
   for i in numbers:
      yield callback(i)

If the function is immutable, then its a bit harder.  The callback has
to be able to do the processing.  You can't use an iterator here
because call stack gets in the way.  You could store the information
being passed to the callback in a list, then iterate over the list
afterwards.  Or you could have the callback be able to handle all of
the work at once.

What do you intend to use this for?  Python has a lot of options and
you may not be using the best one for the problem




More information about the Python-list mailing list