Turning a callback function into a generator

Kirk McDonald kirklin.mcdonald at gmail.com
Mon Jul 3 11:37:28 EDT 2006


cmdrrickhunter at yaho.com wrote:
> 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
> 

It is the function that is immutable.

I am writing a library for the D programming language that is not 
totally unlike Boost.Python:

http://dsource.org/projects/pyd/wiki

It is still in the fairly early stages, although the basic function and 
class wrapping do work.

This particular functionality is required to wrap D's basic iteration 
protocol, the opApply function:

http://www.digitalmars.com/d/statement.html#foreach

opApply works using a callback, as described. Because D does not (yet) 
have anything like Python's "yield", wrapping it with Python's iteration 
interface is turning out to be dreadfully annoying.

-Kirk McDonald



More information about the Python-list mailing list