turning callback into generator

Wai Yip Tung tungwaiyip at yahoo.com
Mon Sep 6 21:00:37 CEST 2004

I'm attempting to turn some process than uses callback to return result  
into a more user friendly generator. I'm hitting some road block so any  
pointer would be appriciated.

Let say there is an existing method producer(x, cb). It calls the supplied  
cb() every time when there is data available. The definititon of cb should  

   def cb(data)

To turn it into generator, I tried:

   def product_generator(x):

   def cb(data):
     yield data

But that's not really the way Python works. 'yield' is not only a  
imperative statement but it also the keyword to signify the containing  
function as a generator function. So in this case product_generator is an  
oridinary function and cb is a generator.

Note that producer() is an existing method that I cannot change. Otherwise  
I might strip the cb and yield directly from the producer().

If python would define another keyword 'generator' to explicit distinguish  
normal function from generator and decouple it from the 'yield' keyword,  
it could perhaps be done that way:

   generator product_generator(x):

   def cb(data):
     yield data

Is this just an syntactic issue or am I hitting on some generator's  
implementation issue? Is there a proper way to do this in Python 2.3?

Thanks for any pointer.

More information about the Python-list mailing list