Need help writing coroutine



I'm working on two coroutines -- one iterates through a huge stream, and
emits chunks in pieces. The other routine takes each chunk, then scores
it as good or bad and passes that score back to the original routine, so
it can make a copy of the stream with the score appended on.

I have the code working, but it just looks really ugly. Here's a vastly
simplified version. One function yields some numbers, and the other
function tells me if they are even or odd.

def parser():
"I just parse and wait for feedback."
for i in 1, 2, 3, 4, 5:
score = (yield i)
if score:
print "%d passed!" % i

def is_odd(n):
"I evaluate each number n, and return True if I like it."
if n and n % 2: return True

def m():
try:
number_generator = parser()
i = None
while 1:
i = number_generator.send(is_odd(i))
except StopIteration: pass

and here's the results when I run this:
In [90]: m()
1 passed!
3 passed!
5 passed!

So, clearly, the code works. But it is nonintuitive for the casual
reader.

I don't like the while 1 construct, I don't like manually
trapping the StopIteration exception, and this line is really ugly:

i = number_generator.send(is_odd(i))

I really like the old for i in parser(): deal, but I can't figure out
how to use .send(...) with that.

Can anyone help me pretty this up? I want to make this as intuitive as
possible.

TIA

Matt

.



Relevant Pages

  • Re: Need help writing coroutine
    ... emits chunks in pieces. ... The other routine takes each chunk, ... score = (yield i) ... def is_odd: ...
    (comp.lang.python)
  • Re: About capture stream data in bda
    ... >> I have studied the ddk samples and it seems to use stream pointer to ... >> transmit the data in routine 'Process'. ... my driver is a pin-centric minidriver. ... >>> where could I capture the stream from device. ...
    (microsoft.public.development.device.drivers)
  • Re: Binary serialization
    ... Previously I would use a file write routine that worked ... DATA members from the class in question the method of writing each ... the base class where you collect the data in to a byte array which is ... then written to the stream by the base class. ...
    (microsoft.public.dotnet.general)
  • Re: Binary or Ascii Text?
    ... interactive scanf and other routines, because the C stream is never ... sure whether the field terminating char has been used or is still ... some other input routine and doesn't have the discipline to define ...
    (comp.lang.c)
  • I need help debugging an MFC OCX
    ... void CFlintCtrl::DoPropExchange(CPropExchange* pPX) ... This routine is called by the framework and always sets m_bReadAhead to ... Where does this stream come from? ...
    (microsoft.public.win32.programmer.ole)